当前位置: 首页 > news >正文

ASP.NET Core对JWT的封装

目录

JWT封装

[Authorize]的注意事项


JWT封装

NuGet 库 |Microsoft.AspNetCore.Authentication.JwtBearer 9.0.1https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearerhttps://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearerhttps://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer

  1. 创建JWTSettings类,配置JWT节点,节点下创建SigningKeyExpireSeconds两个配置项,分别代表JWT的密钥和过期时间(单位:秒)。再创建配置类JWTOptions,包含SigningKey、ExpireSeconds两个属性。
     
    "JWT": {"SecKey": "sdl52%sdf45#$^4sd4f44sdf9*((jksd","ExpireSeconds": 3600
    }
    public class JWTSettings
    {public string SecKey { get; set; }public int ExpireSeconds { get; set; }
    }
  2. Nuget:Microsoft.AspNetCore.Authentication.JwtBearer
  3. 对JWT进行配置
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.IdentityModel.Tokens;
    builder.Services.Configure<JWTSettings>(builder.Configuration.GetSection("JWT"));
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
    {var jwtOpt=builder.Configuration.GetSection("JWT").Get<JWTSettings>();byte[] key = Encoding.UTF8.GetBytes(jwtOpt.SecKey);//设置对称秘钥var secKey = new SymmetricSecurityKey(key);//设置验证参数opt.TokenValidationParameters = new (){ValidateIssuer = false,//是否验证颁发者ValidateAudience = false,//是否验证订阅者ValidateLifetime = true,//是否验证生命周期ValidateIssuerSigningKey = true,//是否验证签名IssuerSigningKey = secKey//签名秘钥};
    });
  4. Program.cs的app.UseAuthorization()这行代码之前添加app.UseAuthentication()
  5. Controller类中进行登录
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DemoContrller : ControllerBase
    {private readonly IOptionsSnapshot<JWTSettings> jwtSettingsOpt;public DemoContrller(IOptionsSnapshot<JWTSettings> jwtSettingsOpt){this.jwtSettingsOpt = jwtSettingsOpt;}[HttpPost]public ActionResult<string> Login(string username, string password){if (username == "admin" && password == "123"){List<Claim> claims = new List<Claim>{new Claim(ClaimTypes.NameIdentifier, "1"),new Claim(ClaimTypes.Name, username)};string key = jwtSettingsOpt.Value.SecKey;DateTime expire = DateTime.Now.AddSeconds(jwtSettingsOpt.Value.ExpireSeconds);byte[] keyBytes = Encoding.UTF8.GetBytes(key);var secKey = new SymmetricSecurityKey(keyBytes);var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);var tokenDescriptor = new JwtSecurityToken(claims: claims,//声明expires: expire,//过期时间signingCredentials: credentials//签名凭据);string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);return jwt;}else{return BadRequest("登录失败");}}
    }
  6. 在需要登录才能访问的控制器类或者Action方法上添加[Authorize]。
  7. 可以使用this.User.FindFirst(ClaimTypes.Name).Value来访问登录用户的身份信息。
  8. 登录和访问。用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. ASP.NET Core会按照HTTP协议的规范,从Authorization取出来令牌,并且进行校验、解析,然后把解析结果填充到User属性中,这一切都是ASP.NET Core完成的,不需要开发人员自己编写代码。但是一旦出现401,没有详细的报错信息,很难排查,这是初学者遇到的难题。
  4. RBAC角色控制:可以设置[Authorize(Roles ="admin,user")]来限制角色登录

http://www.mrgr.cn/news/89888.html

相关文章:

  • 已验证正常,Java输入字符串生成PDF文件
  • xss总结标签
  • OpenHarmonyOS 3.2 编译生成的hap和app文件的名称如何配置追加版本号?
  • 报错:MC1000未知的生成错误Invalid number of sections declared in PE header
  • 【Vim Masterclass 笔记20】第九章:Vim 的个性化设置 + S09L38:Vim 设置与 vimrc 文件的用法示例(一)
  • 【深度学习】关键技术-激活函数(Activation Functions)
  • 基于 SpringBoot3 的 SpringSecurity6 + OAuth2 自定义框架模板
  • MYSQL索引与视图
  • vue2+vue3 HMCXY基础入门
  • 零基础学习书生.浦语大模型--基础岛
  • TCN时间卷积神经网络多变量多步光伏功率预测(Matlab)
  • Ubuntu20.04 本地部署 DeepSeek-R1 及 chatbox可视化
  • C++到C#核心语法对照指南
  • Java并发编程笔记
  • 【抽象代数】1.1. 运算及关系
  • 【DeepSeek论文精读】3. DeepSeekMoE:迈向混合专家语言模型的终极专业化
  • python实现--平衡二叉树和红黑树
  • 大数据数仓实战项目(离线数仓+实时数仓)3
  • vscode卡住---回退版本解决
  • 快速上手Vim的使用
  • 02DevOps基础环境准备
  • Excel 融合 deepseek
  • 深入Linux系列之进程地址空间
  • 基于机器学习时序库pmdarima实现时序预测
  • NetCore Consul动态伸缩+Ocelot 网关 缓存 自定义缓存 + 限流、熔断、超时 等服务治理 + ids4鉴权
  • SQL Server 数据库迁移到 MySQL 的完整指南