.netCore JWT配置 token验证
1.安装 Microsoft.AspNetCore.Authentication.JwtBearer
2.在 appsetting.json 中,添加一个 Jwt 节点
1 2 3 4 5 | "Jwt" : { "SecretKey" : "zhangxigege@qq.com" , "Issuer" : "WebAppIssuer" , "Audience" : "WebAppAudience" }, |
3.JwtHelper类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | ublic class JwtHelper { private readonly IConfiguration _configuration; public JwtHelper(IConfiguration configuration) { _configuration = configuration; } public string CreateToken() { // 1. 定义需要使用到的Claims var claims = new [] { new Claim(ClaimTypes.Name, "u_admin" ), //HttpContext.User.Identity.Name new Claim(ClaimTypes.Role, "r_admin" ), //HttpContext.User.IsInRole("r_admin") new Claim(JwtRegisteredClaimNames.Jti, "admin" ), new Claim( "Username" , "Admin" ), new Claim( "Name" , "超级管理员" ) }; // 2. 从 appsettings.json 中读取SecretKey var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration[ "Jwt:SecretKey" ])); // 3. 选择加密算法 var algorithm = SecurityAlgorithms.HmacSha256; // 4. 生成Credentials var signingCredentials = new SigningCredentials(secretKey, algorithm); // 5. 根据以上,生成token var jwtSecurityToken = new JwtSecurityToken( _configuration[ "Jwt:Issuer" ], //Issuer _configuration[ "Jwt:Audience" ], //Audience claims, //Claims, DateTime.Now, //notBefore DateTime.Now.AddSeconds(30), //expires signingCredentials //Credentials ); // 6. 将token变为string var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); return token; } } |
4.program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | //Swagger文档 var ApiName = "code" ; builder.Services.AddSwaggerGen(s => { s.SwaggerDoc( "v1" , new OpenApiInfo { Version = "v1" , Title = $ "{ApiName} 接口文档——Netcore 6.0" , }); s.OrderActionsBy(o => o.RelativePath); s.IncludeXmlComments( "code.xml" , true ); //设置JWT Bearer token 41行到70行 s.AddSecurityDefinition( "JwtBearer" , new OpenApiSecurityScheme() { Description= "验证" , Name= "Authorization" , In=ParameterLocation.Header, Type=SecuritySchemeType.Http, Scheme= "bearer" }); //定义JwtBearer认证方式二 //options.AddSecurityDefinition("JwtBearer", new OpenApiSecurityScheme() //{ // Description = "这是方式二(JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格))", // Name = "Authorization",//jwt默认的参数名称 // In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中) // Type = SecuritySchemeType.ApiKey //}); //声明一个Scheme,注意下面的Id要和上面AddSecurityDefinition中的参数name一致 var scheme = new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Type = ReferenceType.SecurityScheme, Id = "JwtBearer" } }; //注册全局认证(所有的接口都可以使用认证) s.AddSecurityRequirement( new OpenApiSecurityRequirement() { [scheme] = new string [0] }); }); //JWT 第二步 var configuration = builder.Configuration; builder.Services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true , //是否验证Issuer ValidIssuer = configuration[ "Jwt:Issuer" ], //发行人Issuer ValidateAudience = true , //是否验证Audience ValidAudience = configuration[ "Jwt:Audience" ], //订阅人Audience ValidateIssuerSigningKey = true , //是否验证SecurityKey IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration[ "Jwt:SecretKey" ])), //SecurityKey ValidateLifetime = true , //是否验证失效时间 ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒) RequireExpirationTime = true , }; }); builder.Services.AddSingleton( new JwtHelper(configuration)); |
5.控制器添加
[Authorize]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界