namespace JWTWebApi.JWT; public class JwtOptions { /// <summary> /// 签发者 /// </summary> public string Issuer { get; set; } /// <summary> /// 接收者 /// </summary> public string Audience { get; set; } /// <summary> /// 密钥 /// </summary> public string Key { get; set; } /// <summary> /// 过期时间 /// </summary> public int ExpireSeconds { get; set; } }
"JWT": { "Issuer": "签发方", "Audience": "接受方", "Key": "A86DA130-1B95-4748-B3B2-1B6AA9F2F743",//加密密钥 "ExpireSeconds": 6004 //密钥过期时间 }
using System.Text; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using Microsoft.Extensions.Options; namespace JWTWebApi.JWT; public static class JWTExtensions { public static AuthenticationBuilder AddJWTAuthentication(this IServiceCollection services, IConfiguration configurationManager) { JwtOptions jwtOptions = configurationManager.GetSection("JWT").Get<JwtOptions>(); return services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(x => { x.TokenValidationParameters = new() { ValidateIssuer = true,//是否验证发行商 ValidateAudience = true,//是否验证受众者 ValidateLifetime = true,//是否验证失效时间 ValidateIssuerSigningKey = true,//是否验证签名键 ValidIssuer = jwtOptions.Issuer, ValidAudience = jwtOptions.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Key)) }; }); } }
using System.Security.Claims; namespace JWTWebApi.JWT; public interface IJwtService { string BuildToken(IEnumerable<Claim> claims, JwtOptions options); }
using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.IdentityModel.Tokens; namespace JWTWebApi.JWT; public class JwtService : IJwtService { public string BuildToken(IEnumerable<Claim> claims, JwtOptions options) { //过期时间 TimeSpan timeSpan = TimeSpan.FromSeconds(options.ExpireSeconds);//token过期时间 var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Key));//加密的token密钥 var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);//签名证书,其值为securityKey和HmacSha256Signature算法 var tokenDescriptor = new JwtSecurityToken(options.Issuer, options.Audience, claims, expires: DateTime.Now.Add(timeSpan), signingCredentials: credentials);//表示jwt token的描述信息,其值包括Issuer签发方,Audience接收方,Claims载荷,过期时间和签名证书 return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);//使用该方法转换为字符串形式的jwt token返回 } }
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; namespace JWTWebApi.JWT; public static class SwaggerGenOptionsExtensions { /// <summary> /// 为swagger增加Authentication报文头 /// </summary> /// <param name="option"></param> public static void AddAuthenticationHeader(this SwaggerGenOptions option) { option.AddSecurityDefinition("Authorization", new OpenApiSecurityScheme { Description = "Authorization header. \r\nExample:Bearer 12345ABCDE", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Authorization" } ); ; option.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference=new OpenApiReference { Type=ReferenceType.SecurityScheme, Id="Authorization" }, Scheme="oauth2", Name="Authorization", In=ParameterLocation.Header, }, new List<string>() } }); } }
#region JWT builder.Services.AddScoped<IJwtService, JwtService>(); builder.Services.AddJWTAuthentication(builder.Configuration); builder.Services.Configure<SwaggerGenOptions>(c => { c.AddAuthenticationHeader(); }); #endregion
标签:core,JWT,jwt,Microsoft,options,using,new,net,public From: https://www.cnblogs.com/Insist-Y/p/17452372.html