码迷,mamicode.com
首页 > 其他好文 > 详细

JWT验证

时间:2020-03-23 16:46:18      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:授权   auth   fun   ati   async   thread   clock   core   基本配置   

在.NET Core中想给API进行安全认证,现在最常用的就是Jwt了,简单记录下JWT的使用方法。

一、首先在appsettings.json里写基本配置,参数如下

  "JwtSecurity": {
    "Issuer": "", // 颁发者
    "Audience": "", // 接收者
    "TokenExpires": 7200, // 过期时间,秒为单位
    "SecurityKey": "hello world" // 密钥  
  },

  

二、在Setup里加入限制

            #region JWT验证
            var jwtSecurity = Configuration.GetSection("JwtSecurity");
            var key = jwtSecurity.GetValue<string>("SecurityKey");
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.IncludeErrorDetails = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    RequireExpirationTime = true,
                    ClockSkew = TimeSpan.FromSeconds(0),
                };
                x.Events = new JwtBearerEvents()
                {
                    OnChallenge = new Func<JwtBearerChallengeContext, System.Threading.Tasks.Task>(async target =>
                    {
                        target.HandleResponse();
                        target.Response.ContentType = "application/json";
                        target.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        string result = Newtonsoft.Json.JsonConvert.SerializeObject(new { state = ResultType.TokenOver, message = "授权失败" });
                        await target.Response.WriteAsync(result);
                    }),
                };
            });
            #endregion

三、获取token

        async Task<object> GetToken(UserInfo user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var jwtSecurity = configuration.GetSection("JwtSecurity");
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecurity.GetValue<string>("SecurityKey")));
            var nowTime = DateTime.Now;
            var tokenExpires = nowTime.Add(TimeSpan.FromSeconds(jwtSecurity.GetValue<int>("TokenExpires")));

            var identity = new
            ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName.ToString()));

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = identity,
                Expires = tokenExpires,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return new
            {
                Code = ResultType.Success,
                Token = tokenHandler.WriteToken(token),
                TokenExpireTime = tokenExpires,
            };
        }

 在用户登录的时候,调用上面这个方法就可以获取token了,前端请求接口的时候需要携带token。

 

JWT验证

标签:授权   auth   fun   ati   async   thread   clock   core   基本配置   

原文地址:https://www.cnblogs.com/zhangjd/p/12552750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!