3 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
因?yàn)榫嚯x我問這個(gè)問題已經(jīng)過去一個(gè)多月了。我是這樣做的。
我從 中刪除了以下代碼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>() },
});
我添加了以下一項(xiàng):
c.OperationFilter<AddAuthHeaderOperationFilter>();
當(dāng)然還有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[] { } }
});
}
}
}
很快,這個(gè)OperationFilter類只將儲(chǔ)物柜圖標(biāo)添加到需要授權(quán)的方法中。不過儲(chǔ)物柜總是打開的。所以這不是完美的解決方案,但目前還可以。
它看起來是這樣的:

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
更改為以下內(nèi)容(進(jìn)行了一些額外的樣式編輯):
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 標(biāo)頭定義為參數(shù),Swagger UI 將拒絕發(fā)送該標(biāo)頭。因此,更好的選擇可能是在 SwaggerGen 服務(wù)配置中創(chuàng)建安全定義(通常在 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貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
請按照以下步驟使用正確的掛鎖來實(shí)施 Swagger -
步驟1
添加一個(gè)類并通過接口繼承該類IOperationFilter。之后,實(shí)現(xiàn)接口Apply的方法定義IOperationFilter。
要實(shí)現(xiàn)Apply方法,您需要兩個(gè)類型為OpenApiOperation和的參數(shù)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。在此服務(wù)中,您需要添加我們在步驟 1 中實(shí)現(xiàn)的以下行。
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
構(gòu)建并運(yùn)行。
- 3 回答
- 0 關(guān)注
- 178 瀏覽
添加回答
舉報(bào)