1.1 封装一个SwaggerExtend类(包含JWT配置)
/// <summary> /// Swagger 静态类 /// </summary> public static class SwaggerExtend { /// <summary> /// 添加服务: swagger /// </summary> /// <param name="services"></param> /// <returns></returns> public static void AddCustSwagger(this IServiceCollection services) { var version = "V1.0"; var apiName = "XXX系统"; services.AddSwaggerGen(options => { options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); options.SwaggerDoc("system_v1", new OpenApiInfo { Version = version, Title = $"{apiName} API", Description = $"{apiName} {version} 接口服务" }); // 获取应用程序所在目录 var basePath = Path.GetDirectoryName(typeof(SwaggerExtend).Assembly.Location); var xmlPath = Path.Combine(basePath, "dichanweb.xml"); // swagger界面默认只显示 方法&字段 注释,不显示 控制器注释 // 第二个参数为true, 则是controller的注释 //options.IncludeXmlComments(xmlPath); options.IncludeXmlComments(xmlPath, true); options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer { token }\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "Bearer", BearerFormat = "JWT", }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference=new OpenApiReference() { Id="Bearer", Type=ReferenceType.SecurityScheme } }, new string[]{} } }); }); services.AddAuthentication(option => { option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { string Jwt_Issuer = "test.cn"; string Jwt_Audience = "test"; string Jwt_SecretKey = "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true, ValidIssuer = Jwt_Issuer, ValidAudience = Jwt_Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Jwt_SecretKey)) }; }); } /// <summary> /// 添加中间件: swagger /// </summary> /// <param name="app"></param> public static void UseCustSwagger(this IApplicationBuilder app) { app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/system_v1/swagger.json", "系统API"); // 默认路径为:/swagger/index.html // 路由前缀 - 设置为空,可直接跳转到swagger页面:/index.html // api测试可设置为空,部署时容易与前端路由冲突 options.RoutePrefix = string.Empty; // 禁用Swagger UI的自动跳转行为 //options.EnableValidator(); options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None); }); } }
1.2注入
builder.Services.AddCustSwagger(); /*认证*/ app.UseAuthentication(); /*授权*/ app.UseAuthorization();
1.3 用户登录后返回TOKEN的方法
private string GenerateJwtToken(T_User user) { string Jwt_Issuer = "test.cn"; string Jwt_Audience = "test"; string Jwt_SecretKey = "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789"; var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.FMobilePhone) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Jwt_SecretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: Jwt_Issuer, audience: Jwt_Audience, claims: claims, expires: DateTime.UtcNow.AddHours(1), signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token); }
参考:https://www.cnblogs.com/CRobot/p/16715909.html
标签:swagger,string,JWT,Jwt,var,new,NET,Swagger,options From: https://www.cnblogs.com/linyijia/p/18260489