NETCORE - JWT认证与授权
NETCORE - JWT认证与授权
1. 安装NuGet包:JwtBearer
2. 配置 签名参数
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "TokenParameter": { "Issuer": "颁发者", //颁发者 "Audience": "接收者", //接收者 "Secret": "123456732409ldjfsd8", //签名秘钥 "AccessExpiration": 30 //AccessToken过期时间(分钟)" }, "AllowedHosts": "*" }
新建配置类
public class TokenParameter { public string Issuer { get; set; }//颁发者 public string Audience { get; set; }//接收者 public string Secret { get; set; }//签名秘钥 public int AccessExpiration { get; set; }//AccessToken过期时间(分钟) }
在Startup中 注入config配置
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //注入config配置 services.Configure<TokenParameter>(Configuration.GetSection("TokenParameter")); }
3. 定义一个获取token的控制器
[Route("api/[controller]")] [ApiController] public class OAuthController : ControllerBase { private TokenParameter Config_TokenParameter; public OAuthController(IOptions<TokenParameter> option) { Config_TokenParameter = option.Value; } [HttpGet] [Route("token")] public ActionResult GetAccessToken(string username, string password) { if (username != "admin" || password != "admin") { return BadRequest("Invalid Request"); } var claims = new[] { new Claim (ClaimTypes.Name,username), new Claim(ClaimTypes.Role,"") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Config_TokenParameter.Secret)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwtToken = new JwtSecurityToken(Config_TokenParameter.Issuer, Config_TokenParameter.Audience, claims, expires: DateTime.UtcNow.AddMinutes(Config_TokenParameter.AccessExpiration), signingCredentials: credentials); var token = new JwtSecurityTokenHandler().WriteToken(jwtToken); return Ok(token); } }
4. 添加token身份认证到容器(startup)
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //注入config配置 services.Configure<TokenParameter>(Configuration.GetSection("TokenParameter")); //获取ServiceProvider var serviceProvider = services.BuildServiceProvider(); //取出放入静态变量 var Config_TokenParameter = serviceProvider.GetService<IOptions<TokenParameter>>(); //添加token身份认证到容器 services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuerSigningKey = true,//是否调用对签名securityToken的SecurityKey进行验证 IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Config_TokenParameter.Value.Secret)),//签名秘钥 ValidateIssuer = true,//是否验证颁发者 ValidIssuer = Config_TokenParameter.Value.Issuer,//颁发者 ValidateAudience = true,//是否验证接收者 ValidAudience = Config_TokenParameter.Value.Audience,//接收者 ValidateLifetime = true,//是否验证失效时间 }; }); }
添加身份认证到中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication();//必须在app.UseAuthorization();之前 app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
添加测试控制器
需要授权的方法 需加上 [Authorize],给方法或者控制器标记均可
如标记[AllowAnonymous],则此方法不需要身份验证(比如登录接口)
[Route("api/[controller]")] [ApiController] public class textController : ControllerBase { [HttpGet] [Route("GetTodo")] [Authorize] public ActionResult GetTodo() { return Ok("request ok !"); } }
postman测试
1. 直接调用GetTodo,失败,返回401
https://localhost:5001/api/text/GetTodo
2. 获取token,直接访问
https://localhost:5001/api/oauth/token?username=admin&password=admin
3.添加 token 再访问 GetTodo,访问成功。
https://localhost:5001/api/text/GetTodo
项目:NETCORE.JWT
附代码:https://gitee.com/wuxincaicai/NETCORE.git
引用:https://segmentfault.com/a/1190000037433091
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
2019-11-04 Jenkins-在CentOS7 上安装配置