.NET Core 3.1 Swagger 使用 JWT

时间:2025-03-27 17:49:15
public void ConfigureServices(IServiceCollection services) { //注册 Swagger 服务 services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "HimCloud API", Version = "v1" }); //获取xml文件名 var xmlFile = $"{().GetName().Name}.xml"; //获取xml文件路径 var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); // 添加控制器层注释,true表示显示控制器注释 options.IncludeXmlComments(xmlPath, true); #region swagger 用 Jwt验证 //开启权限小锁 options.OperationFilter<AddResponseHeadersFilter>(); options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>(); //在header中添加token,传递到后台 options.OperationFilter<SecurityRequirementsOperationFilter>(); options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "JWT授权(数据将在请求头中进行传递)直接在下面框中输入Bearer {token}(注意两者之间是一个空格) \"", Name = "Authorization",//jwt默认的参数名称 In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中) Type = SecuritySchemeType.ApiKey }); #endregion }); //添加jwt验证: services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,//是否验证Issuer ValidateAudience = true,//是否验证Audience ValidateLifetime = true,//是否验证失效时间 ValidateIssuerSigningKey = true,//是否验证SecurityKey ValidAudience = "AESCR",//Audience ValidIssuer = "AESCR",//Issuer,这两项和后面签发jwt的设置一致 ClockSkew = TimeSpan.Zero, // // 默认允许 300s 的时间偏移量,设置为0 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:SecurityKey"]))//拿到SecurityKey }; }); services.AddControllers(); }