Ejemplo n.º 1
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var apiParam = context.ActionArguments.Values.SingleOrDefault(x => x is ApiParamInfo);

            if (apiParam == null)
            {
                context.Result = new NotFoundObjectResult("参数错误,请求失败");
                return;
            }

            var data = apiParam as ApiParamInfo;

            if (data.Params == null || string.IsNullOrEmpty(data.Sign))
            {
                context.Result = new BadRequestObjectResult("签名为空,请求无效");
                return;
            }

            if (string.IsNullOrEmpty(data.TimeStamp) || !long.TryParse(data.TimeStamp, out long timeStamp))
            {
                context.Result = new BadRequestObjectResult("时间戳错误,请求无效");
                return;
            }

            //验签
            SortedDictionary <string, string> paras = new SortedDictionary <string, string>(data.Params);

            if (!SecuritySign.VerifyWithTimeStamp(paras, data.Sign, timeStamp))
            {
                context.Result = new BadRequestObjectResult("验签失败,请求无效");
                return;
            }

            var token = data.RequestId;

            //请求唯一性校验
            if (!TokenManager.GetInstance.Add(token))
            {
                token = string.Empty;
            }

            if (!string.IsNullOrEmpty(token))
            {
                base.OnActionExecuting(context);
            }
            else
            {
                context.Result = new BadRequestObjectResult("请求参数无效:" + token);
                return;
            }
        }
Ejemplo n.º 2
0
        private async Task GenerateToken(HttpContext context, Services.Contracts.IAccountService accountService)
        {
            var auth_success = false;
            var username     = context.Request.Form["username"];
            var password     = context.Request.Form["password"];

            var authentication = context.Request.Form["authentication"];

            if (!string.IsNullOrEmpty(authentication))
            {
                var dynamic = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(authentication.ToString().SafeDecoded());
                SortedDictionary <string, string> sArray = new SortedDictionary <string, string>();
                sArray.Add("UserName", dynamic.UserName.ToString());
                sArray.Add("TimeStamp", dynamic.TimeStamp.ToString());
                sArray.Add("Sign", dynamic.Sign.ToString());

                if (SecuritySign.VerifyWithTimeStamp(sArray, sArray["Sign"], Convert.ToInt64(sArray["TimeStamp"])))
                {
                    auth_success = true;
                    username     = dynamic.UserName.ToString();
                }
                else
                {
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                    await context.Response.WriteAsync("Invalid authentication.");
                }
            }

            if (!auth_success)
            {
                var identity = await _options.IdentityResolver(username, password, accountService);

                if (identity == null)
                {
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                    await context.Response.WriteAsync("Invalid username or password.");

                    return;
                }
            }

            var userInfo = await accountService.GetUserAuthInfo(username);

            var now = DateTime.UtcNow;

            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, username),
                new Claim(JwtRegisteredClaimNames.Jti, await _options.NonceGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
                new Claim(JwtClaimNamesConst.Org, userInfo.OrganizationId.ToString(), ClaimValueTypes.String),
                new Claim(JwtClaimNamesConst.UseName, userInfo.Name, ClaimValueTypes.String),
                new Claim(JwtClaimNamesConst.Func, string.Join(",", userInfo.Functions.Select(x => x.ToString()).ToArray()))
            };

            // Create the JWT and write it to a string
            var jwt = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(_options.Expiration),
                signingCredentials: _options.SigningCredentials);
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                expires_in   = (int)_options.Expiration.TotalSeconds,
                user_name    = userInfo.Name,
                user_func    = string.Join(",", userInfo.Functions.Select(x => x.ToString()).ToArray())
            };

            // Serialize and return the response
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));
        }