Example #1
0
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            //判断是否匿名访问的接口或控制器
            if (!context.ActionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(false).Any() &&
                !context.ActionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(false).Any())
            {
                string token = "";
                //从url中获取token
                var qs = context.Request.GetQueryNameValuePairs().ToDictionary(i => i.Key, i => i.Value);
                if (qs.ContainsKey("token"))
                {
                    token = qs["token"];
                }
                else
                {
                    var httpContext = context.Request.GetHttpContext();
                    token = httpContext.Request["token"];
                }
                if (string.IsNullOrWhiteSpace(token) || Regex.Matches(token, @"\.").Count != 4)
                {
                    throw new HttpResponseException(HttpStatusCode.Unauthorized);
                }

                //解析token荷载部分
                JwePayload payload = null;
                try
                {
                    payload = JweProvider.Decode(token, JwtCommon.SignKey);
                }
                catch (Exception e)
                {
                    LogProvider.Error.Error(e, "解析jwepayload失败");
                }
                if (payload == null)
                {
                    throw new HttpResponseException(HttpStatusCode.Unauthorized);
                }
                //判断是否过期
                if (payload.IsExpires())
                {
                    throw new HttpResponseException(HttpStatusCode.Unauthorized);
                }
                var user = await InjectionContainer.Resolve <IUserStorage>().GetAsync(payload.uid);

                if (user == null)
                {
                    throw new HttpResponseException(HttpStatusCode.Unauthorized);
                }
                //保存user
                context.Request.Properties.Add(HttpPropertyKeys.AuthorizedUser, user);
                //保存jwe payload
                context.Request.Properties.Add(HttpPropertyKeys.JwePayload, payload);
            }
        }
        public async Task <IHttpActionResult> LoginAsync(User json)
        {
            if (json == null)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string vcode = "";

            if (!CacheProvider.TryGet("vcode." + json.sid, out vcode) || vcode != json.vcode)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "验证码错误");
            }
            if (string.IsNullOrEmpty(json.username))
            {
                throw new BadRequestException(ResultCode.ArgumentException, "登录用户名不能为空");
            }
            if (string.IsNullOrEmpty(json.password))
            {
                throw new BadRequestException(ResultCode.ArgumentException, "登录密码不能为空");
            }

            string password = HashAlgorithmProvider.ComputeHash("MD5", json.password, true);
            var    user     = await this.m_UserStorage.GetAsync(json.username);

            if (user == null || user.password != password)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "用户名或密码错误");
            }
            if (user.status != 1)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "用户已禁用,请联系管理员");
            }

            //remove validate code
            CacheProvider.Remove("vcode." + json.sid);

            var data = new
            {
                user.username,
                user.nickname,
                access_token = JweProvider.Encode(JwtCommon.SignKey, user.id, JwtCommon.ExpireInMinutes),
                expires      = DateTimeUtil.GetTimestamp(DateTime.Now.AddHours(2))
            };

            return(Json(JsonApiResult.Ok(data)));
        }