ASP.NET Core WebAPI中使用JWT Bearer认证和授权

 

1、添加包

Microsoft.AspNetCore.Authentication.JwtBearer

2、在Startup类的ConfigureServices方法里面注入服务:

ASP.NET Core WebAPI中使用JWT Bearer认证和授权
  public void ConfigureServices(IServiceCollection services)
        {

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
          .AddJwtBearer(options =>
          {
              options.TokenValidationParameters = new TokenValidationParameters
              {
                  SaveSigninToken = true,//保存token,后台验证token是否生效(重要)
                      ValidateIssuer = true,//是否验证Issuer
                      ValidateAudience = true,//是否验证Audience
                      ValidateLifetime = true,//是否验证失效时间
                      ValidateIssuerSigningKey = true,//是否验证SecurityKey
                      ValidAudience = "sukcore",//Audience
                      ValidIssuer = "sukcore",//Issuer,这两项和前面签发jwt的设置一致
                      IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("BB3647441FFA4B5DB4E64A29B53CE525"))
              };
              options.Events = new JwtBearerEvents()
              {
                  OnChallenge = context =>
                  {
                      context.HandleResponse();
                      context.Response.Clear();
                      context.Response.ContentType = "application/json";
                      context.Response.StatusCode = 401;
                      context.Response.WriteAsync(new { message = "授权未通过", status = false, code = 401 }.Serialize());
                      return Task.CompletedTask;
                  }
              };
          });

        }
public void ConfigureServices(IServiceCollection services)

 3、在Startup类的Configure方法里面添加 

ASP.NET Core WebAPI中使用JWT Bearer认证和授权
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {              
            //身份验证
            app.UseAuthentication();
            //授权
            app.UseAuthorization();             
        }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

4、接下来做权限校验

在需要授权的api控制器或者Action上新增 [Authorize] 标记

 

ASP.NET Core WebAPI中使用JWT Bearer认证和授权
public class TokenService : ITokenService
    {
        private readonly JwtSetting _jwtSetting;
        public TokenService(IOptions<JwtSetting> option)
        {
            _jwtSetting = option.Value;
        }

        public string GetToken(UserEntity user)
        {
            //创建用户身份标识,这里可以随意加入自定义的参数,key可以自己随便起
            var claims = new[]
            {
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                    new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
                    new Claim(ClaimTypes.NameIdentifier, user.username.ToString()),
                    new Claim("Id", user.id.ToString()),
                    new Claim("Name", user.username.ToString())
                };
            //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSetting.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
            var token = new JwtSecurityToken(
                //颁发者
                issuer: _jwtSetting.Issuer,
                //接收者
                audience: _jwtSetting.Audience,
                //过期时间
                expires: DateTime.Now.AddMinutes(30),
                //签名证书
                signingCredentials: creds,
                //自定义参数
                claims: claims
                );
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return jwtToken;
        }
    }
public string GetToken(UserEntity user)
ASP.NET Core WebAPI中使用JWT Bearer认证和授权
/// <summary>
    /// 权限(获取Token)
    /// </summary>
    [Route("api/[controller]/[action]")]
    public class AuthController : ApiController
    {
        private readonly ITokenService _tokenService;
        /// <summary>
        /// 
        /// </summary>
        public AuthController(ITokenService tokenService)
        {
            _tokenService = tokenService;
        }
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public MethodResult GetToken(UserEntity user)
        {
            var token = _tokenService.GetToken(user);
            var response = new
            {
                Status = true,
                Token = token,
                Type = "Bearer"
            };
            return new MethodResult(response);
        }
    }
public class AuthController : ApiController
ASP.NET Core WebAPI中使用JWT Bearer认证和授权
public class UserEntity
    {
        /// <summary>
        /// ID
        /// </summary>
        public int id { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string username { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string password { get; set; }

    }
public class UserEntity
ASP.NET Core WebAPI中使用JWT Bearer认证和授权
public class JwtSetting
    {
        /// <summary>
        /// 颁发者
        /// </summary>
        public string Issuer { get; set; }

        /// <summary>
        /// 接收者
        /// </summary>
        public string Audience { get; set; }

        /// <summary>
        /// 令牌密码
        /// </summary>
        public string SecurityKey { get; set; }

        /// <summary>
        ///  过期时间
        /// </summary>
        public long ExpireSeconds { get; set; }

        /// <summary>
        /// 签名
        /// </summary>
        public SigningCredentials Credentials
        {
            get
            {
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey));
                return new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            }
        }
    }
public class JwtSetting

 

参考如下链接

https://www.cnblogs.com/ZhengHengWU/p/12574045.html

 

ASP.NET Core WebAPI中使用JWT Bearer认证和授权

上一篇:Windows安装程序无法将Windows配置未在此计算机的硬件上运行--解决方法


下一篇:Wind量化接口常见错误码(ErrorCode)意义