Asp.net Core Jwt使用总结(二)Jwt配置及使用详解
小白浏览:3502023-09-20 14:37:30本文累计收益:0我也要赚钱
一、初始化配置数据

在appsettings.json文件中配置JWT节点,节点下创建SigningKey、ExpireSeconds两个配置项,分别代表JWT的密钥和过期时间(单位:秒)。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "JWT": {
    "SecKey": "sdfarwer8sdf7sd6f6^#dfsdfdsf",
    "ExpireSeconds": 3600
  }
}

再创建配置类JWTOptions,包含SigningKey、ExpireSeconds两个属性。

namespace JWTTest
{
    public class JWTOptions
    {
        public string SecKey { get; set; }
        public int ExpireSeconds { get; set; }
    }
}
二、引入JWT包

Nuget:Microsoft.AspNetCore.Authentication.JwtBearer

三、在Program.cs文件中对JWT进行配置
//获取配置信息
services.Configure<JWTOptions>(builder.Configuration.GetSection("JWT"));
//Jwt校验配置
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
       var jwtOpt = builder.Configuration.GetSection("JWT").Get<JWTOptions>();
       byte[] keyBytes = Encoding.UTF8.GetBytes(jwtOpt.SigningKey);
       var secKey = new SymmetricSecurityKey(keyBytes);
       x.TokenValidationParameters = new()
       {
             ValidateIssuer=false, ValidateAudience=false, ValidateLifetime=true,
              ValidateIssuerSigningKey=true, IssuerSigningKey=secKey
      };
 });
四、添加app.UseAuthentication()中间件

在Program.cs文件的app.UseAuthorization()这行代码之前添加app.UseAuthentication()

五、Controller类中进行登录测试
namespace JWTTest.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        //获取配置文件
        private readonly IOptionsSnapshot<JWTOptions> jWTOptions;
        public LoginController(IOptionsSnapshot<JWTOptions> jWTOptions)
        {
            this.jWTOptions = jWTOptions;
        }
        /// <summary>
        /// 登录并返回Jwt代码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<string?> Login(string userName, string password)
        {
            if (userName == "admin" && password == "666666")
            {
                List<Claim> claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, "1"));
                //读取配置文件
                string key = jWTOptions.Value.SecKey;
                //超时时间
                DateTime expires = DateTime.Now.AddSeconds(jWTOptions.Value.ExpireSeconds);
                byte[] secBytes = Encoding.UTF8.GetBytes(key);
                var secKey = new SymmetricSecurityKey(secBytes);
                var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
                var tokenDescriptor = new JwtSecurityToken(claims: claims, expires: expires, signingCredentials: credentials);
                return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
            }
            else
            {
                return BadRequest();
            }
        }
    }
}
6、权限认证的使用

在需要登录才能访问的控制器类或者Action方法上添加[Authorize] 

[HttpGet]
[Authorize]
public ActionResult<string?> Test1()
{
      return "ok";
}
7、测试登录和访问。

用PostMan自定义报文头,Authorization的值为“Bearer JWTToken”, Authorization的值中的“Bearer”和JWT令牌之间一定要通过空格分隔。前后不能多出来额外的空格、换行等。

[Authorize]的注意事项
1、ASP.NET Core中身份验证和授权验证的功能由Authentication、Authorization中间件提供:app.UseAuthentication()、app.UseAuthorization() 。
2、控制器类上标注[Authorize],则所有操作方法都会被进行身份验证和授权验证;对于标注了[Authorize]的控制器中,如果其中某个操作方法不想被验证,可以在操作方法上添加[AllowAnonymous]。如果没有在控制器类上标注[Authorize],那么这个控制器中的所有操作方法都允许被自由地访问;对于没有标注[Authorize]的控制器中,如果其中某个操作方法需要被验证,我们也可以在操作方法上添加[Authorize]。
3、在Action方法内使用this.User.FindFirst(ClaimTypes.Name)获取JWT中的用户信息。
4、如果在Action方法上添加[Authorize(Roles=”admin”)],则要求用户必须有admin角色权限才可以访问。构造JWT时需要添加角色信息,claims.Add(new Claim(ClaimTypes.Role, "admin"));
5、ASP.NET Core会按照HTTP协议的规范,从Authorization取出来令牌,并且进行校验、解析,然后把解析结果填充到User属性中,这一切都是ASP.NET Core完成的,不需要开发人员自己编写代码。但是一旦出现401,没有详细的报错信息,很难排查,这是初学者遇到的难题。

 

本文附件(20230920143730JWTTest实例.rar)价格:0
评论列表
发表评论
+ 关注