abp版本:
abp 2.9.0
Swashbuckle.AspNetCore 5.4.1
使用Abp cli 创建项目后,启动项目跳转至swagger页面,此时项目未启动token认证的,对于配置了权限访问的接口是无法访问的(返回401)
swagger 开启bearer token 认证
根据网上配置,在ConfigureServices中增加代码:
context.Services.AddSwaggerGen( options => { options.SwaggerDoc("v1", new OpenApiInfo {Title = "API", Version = "v1"}); options.DocInclusionPredicate((docName, description) => true); options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Name = "Authorization", Scheme = "Bearer", Description = "Specify the authorization token.", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, }); options.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference {Type = ReferenceType.SecurityScheme, Id = "Bearer"} }, new string[] { } }, }); });
配置后启动项目,可以在swagger界面看到绿锁标志
输入token后,仍然无法访问需要权限的接口,查看请求发现,token未通过header发送出去
再查询后发现,swagger 3.0后 配置发生了改变,Scheme的设置强制使用小写字母,使用大写字母开头,则swagger界面将不会传输请求头,最后可使用的配置修改如下:
context.Services.AddSwaggerGen( options => { options.SwaggerDoc("v1", new OpenApiInfo {Title = "API", Version = "v1"}); options.DocInclusionPredicate((docName, description) => true); options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Name = "Authorization", Scheme = "bearer", Description = "Specify the authorization token.", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, }); options.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference {Type = ReferenceType.SecurityScheme, Id = "Bearer"} }, new string[] { } }, }); });