3 回答
TA贡献1824条经验 获得超5个赞
因为距离我问这个问题已经过去一个多月了。我是这样做的。
我从 中删除了以下代码Startup.cs:
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
In = "header",
Description = "Please enter into field the word 'Bearer' following by space and your JWT token",
Name = "Authorization",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", Enumerable.Empty<string>() },
});
我添加了以下一项:
c.OperationFilter<AddAuthHeaderOperationFilter>();
当然还有AddAuthHeaderOperationFilter.cs:
public class AddAuthHeaderOperationFilter : IOperationFilter
{
private readonly IHttpContextAccessor httpContextAccessor;
public AddAuthHeaderOperationFilter(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public void Apply(Operation operation, OperationFilterContext context)
{
var filterDescriptor = context.ApiDescription.ActionDescriptor.FilterDescriptors;
var isAuthorized = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
var allowAnonymous = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);
if (isAuthorized && !allowAnonymous)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "Authorization",
In = "header",
Description = "JWT access token",
Required = true,
Type = "string",
//Default = $"Bearer {token}"
});
operation.Responses.Add("401", new Response { Description = "Unauthorized" });
operation.Responses.Add("403", new Response { Description = "Forbidden" });
operation.Security = new List<IDictionary<string, IEnumerable<string>>>();
//Add JWT bearer type
operation.Security.Add(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});
}
}
}
很快,这个OperationFilter类只将储物柜图标添加到需要授权的方法中。不过储物柜总是打开的。所以这不是完美的解决方案,但目前还可以。
它看起来是这样的:
TA贡献1860条经验 获得超9个赞
更改为以下内容(进行了一些额外的样式编辑):
public class AddAuthHeaderOperationFilter : IOperationFilter
{
private readonly IHttpContextAccessor httpContextAccessor;
public AddAuthHeaderOperationFilter(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public void Apply(Operation operation, OperationFilterContext context)
{
var filterDescriptor = context.ApiDescription.ActionDescriptor.FilterDescriptors;
var isAuthorized = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
var allowAnonymous = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);
if (isAuthorized && !allowAnonymous)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "Authorization",
In = "header",
Description = "JWT access token",
Required = true,
Type = "string"
});
operation.Responses.Add("401", new Response { Description = "Unauthorized" });
operation.Responses.Add("403", new Response { Description = "Forbidden" });
operation.Security = new List<IDictionary<string, IEnumerable<string>>>();
//Add JWT bearer type
operation.Security.Add(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});
}
}
}
编辑
如果将 Authorization 标头定义为参数,Swagger UI 将拒绝发送该标头。因此,更好的选择可能是在 SwaggerGen 服务配置中创建安全定义(通常在 Startup.ConfigureServices 中):
public void ConfigureServices(IServiceCollection services)
{
// Service configuration
services.AddSwaggerGen(c =>
{
// Configure Swagger
// "Bearer" is the name for this definition. Any other name could be used
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Use bearer token to authorize",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT"
});
}
}
然后添加安全要求以及对操作定义的引用:
public class AddAuthorizationHeaderOperationHeader : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var actionMetadata = context.ApiDescription.ActionDescriptor.EndpointMetadata;
var isAuthorized = actionMetadata.Any(metadataItem => metadataItem is AuthorizeAttribute);
var allowAnonymous = actionMetadata.Any(metadataItem => metadataItem is AllowAnonymousAttribute);
if (!isAuthorized || allowAnonymous)
{
return;
}
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
operation.Security = new List<OpenApiSecurityRequirement>();
//Add JWT bearer type
operation.Security.Add(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
// Definition name.
// Should exactly match the one given in the service configuration
Id = "Bearer"
}
}, new string[0]
}
}
);
}
}
TA贡献1886条经验 获得超2个赞
请按照以下步骤使用正确的挂锁来实施 Swagger -
步骤1
添加一个类并通过接口继承该类IOperationFilter。之后,实现接口Apply的方法定义IOperationFilter。
要实现Apply方法,您需要两个类型为OpenApiOperation和的参数OpenApiOperation。
public class AddSwaggerService : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var actionMetadata = context.ApiDescription.ActionDescriptor.EndpointMetadata;
var isAuthorized = actionMetadata.Any(metadataItem => metadataItem is AuthorizeAttribute);
var allowAnonymous = actionMetadata.Any(metadataItem => metadataItem is AllowAnonymousAttribute);
if (!isAuthorized || allowAnonymous)
{
return;
}
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
operation.Security = new List<OpenApiSecurityRequirement>();
var security = new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
}, new List<string>()
}
};
//add security in here
operation.Security.Add(security);
}
第2步
添加swagger Generation Service在ConfigureServices方法中Startup.cs。在此服务中,您需要添加我们在步骤 1 中实现的以下行。
c.OperationFilter<AddSwaggerService>();
public void ConfigureServices(IServiceCollection services)
{
//.........other Services.........
//.........other Services.........
//.........other Services.........
services.AddSwaggerGen(c =>
c.SwaggerDoc(AppConstantKeys.APIName, new OpenApiInfo { Title = "title", Version = "APIVersion" });
c.OperationFilter<AddSwaggerService>();
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description ="SwaggerShortDescription",
Name = "HeaderName",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
});
});
//.........other Services.........
//.........other Services.........
//.........other Services.........
}
Step-3 在中间件管道中添加 swagger。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//.........other middlewares.........
//.........other middlewares.........
//.........other middlewares.........
//.........other middlewares.........
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerUIName");
c.DocumentTitle = "SwaggerUITitle";
c.DocExpansion(DocExpansion.None);
c.RoutePrefix = string.Empty;
});
//.........other middlewares.........
//.........other middlewares.........
//.........other middlewares.........
//.........other middlewares.........
}
步骤4
构建并运行。
- 3 回答
- 0 关注
- 129 浏览
添加回答
举报