Bag*_*yer 31 swagger swagger-ui swashbuckle
我创建了一个使用个人帐户安全的asp.net webapi应用程序,以便默认启用Bearer令牌.它工作正常,所以我能够在Postman中测试它们没有问题.
当我尝试通过Swashbuckle集成Swagger UI时,问题就出现了.我通过以下方式安装了Swashbuckle:
Install-Package Swashbuckle
然后更改SwaggerConfig.cs:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.ApiKey("Token")
.Description("Filling bearer token here")
.Name("Authorization")
.In("header");
}
.EnableSwaggerUi(c =>
{
c.EnableApiKeySupport("Authorization", "header");
};
Run Code Online (Sandbox Code Playgroud)
启动我的应用程序并填写Bearer令牌:
但是当我运行需要授权的api请求时,它不起作用.这是截图:
承载令牌被添加到标头中的Authorization.但我仍然得到错误401.我想知道是否因为令牌被编码(SPACE被%20取代)?任何的想法?谢谢.
顺便说一句,我想知道如何在我的Swagger文档中添加/ token,以便我可以在Swagger UI中获取令牌.
uri*_*rig 18
现在,Swashbuckle v5.5.0解决了下面详述的问题.
刚遇到完全相同的问题.我认为根本原因是Swashbuckle源代码中的这一行:
var key = encodeURIComponent($('#input_apiKey')[0].value);
Run Code Online (Sandbox Code Playgroud)
这是HTML输入字段的值通过URL编码转换空间的位置%20.我打算在GitHub上的Swashbuckle回购中打开一个问题.
在该问题得到解决之前,这里有一个解决方法,它基于使用注入Swagger UI的Javascript文件替换上面的行:
在安装了Swashbuckle的项目中,创建一个新文件夹并将其命名为"Swagger".
在新文件夹中创建一个名为"SwaggerUiCustomization.js"的新Javascript文件,并将此脚本放入其中:
(function () {
function addApiKeyAuthorization() {
var key = $('#input_apiKey')[0].value;
if (key && key.trim() != "") {
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization(swashbuckleConfig.apiKeyName, key, swashbuckleConfig.apiKeyIn);
window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
log("added key " + key);
}
}
$('#input_apiKey').change(addApiKeyAuthorization);
})();
Run Code Online (Sandbox Code Playgroud)在Solution Explorer中,选择文件并按Alt + Enter编辑其属性.在属性窗口中更改文件的生成操作,以嵌入的资源.
在SwaggerConfig.cs文件中,在EnableSwaggerUi()代码块中添加以下行:
c.InjectJavaScript(thisAssembly,
"<Project_Default_Namespace>.Swagger.SwaggerUiCustomization.js");
当然,请确保替换<Project_Default_Namespace>为项目的默认命名空间.
运行项目并在文本框中输入"Bearer".当您调用控制器操作时,您应该%20%在服务器端获得完全相同的值 - 使用空格而不是- .
Ehs*_*jad 11
在 asp.net 框架 Web API 中,我能够在 UI 上添加不记名令牌并通过两种不同的方式使其正常工作。
添加操作过滤器。创建以下类:
public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
{
operation.parameters = new List<Parameter>();
}
operation.parameters.Add(new Parameter
{
name = "Authorization",
@in = "header",
description = "access token",
required = false,
type = "string",
@default = "Bearer "
});
}
}
Run Code Online (Sandbox Code Playgroud)
现在在 SwaggerConfig.cs 中添加以下内容:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
// other settings
c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
})
.EnableSwaggerUi(c =>
{
// UI configurations
});
Run Code Online (Sandbox Code Playgroud)
我们也可以使用 DocumentFilter 来迭代所有操作并添加标头,在下面的操作中我们跳过实际获取用户名和密码并第一次给出令牌的操作:
public class SwaggerPathDescriptionFilter : IDocumentFilter
{
private string tokenUrlRoute = "Auth";
// the above is the action which returns token against valid credentials
private Dictionary<HeaderType, Parameter> headerDictionary;
private enum HeaderType { TokenAuth };
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
CreateHeadersDict();
var allOtherPaths = swaggerDoc.paths.Where(entry => !entry.Key.Contains(tokenUrlRoute)) //get the other paths which expose API resources and require token auth
.Select(entry => entry.Value)
.ToList();
foreach (var path in allOtherPaths)
{
AddHeadersToPath(path, HeaderType.TokenAuth);
}
}
/// <summary>
/// Adds the desired header descriptions to the path's parameter list
/// </summary>
private void AddHeadersToPath(PathItem path, params HeaderType[] headerTypes)
{
if (path.parameters != null)
{
path.parameters.Clear();
}
else
{
path.parameters = new List<Parameter>();
}
foreach (var type in headerTypes)
{
path.parameters.Add(headerDictionary[type]);
}
}
/// <summary>
/// Creates a dictionary containin all header descriptions
/// </summary>
private void CreateHeadersDict()
{
headerDictionary = new Dictionary<HeaderType, Parameter>();
headerDictionary.Add(HeaderType.TokenAuth, new Parameter() //token auth header
{
name = "Authorization",
@in = "header",
type = "string",
description = "Token Auth.",
required = true,
@default = "Bearer "
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后我们需要在 SwaggerConfig.cs 中注册它:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
// other settings
c.DocumentFilter<SwaggerPathDescriptionFilter>();
})
.EnableSwaggerUi(c =>
{
// UI configurations
});
Run Code Online (Sandbox Code Playgroud)
现在我们将在 swagger UI 中看到标题的 Token 输入,例如:
注意:此示例使用 Json Web 令牌。
可以设置您的代码,以便授权字符串中不需要“Bearer”。
WebApi 项目中用于检索令牌的代码(请参阅下面代码段中的令牌 = ...):
private static bool TryRetrieveToken(HttpRequestMessage request, out string token)
{
token = null;
IEnumerable<string> authzHeaders;
if (!request.Headers.TryGetValues("Authorization", out authzHeaders) || authzHeaders.Count() > 1)
{
return false;
}
var bearerToken = authzHeaders.ElementAt(0);
token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
return true;
}
Run Code Online (Sandbox Code Playgroud)
Swagger ApiKey:
c.ApiKey("Authorization")
.Description("Filling bearer token here")
.Name("Bearer")
.In("header");
Run Code Online (Sandbox Code Playgroud)
Swagger 启用 ApiKey 支持:
c.EnableApiKeySupport("Authorization", "header");
Run Code Online (Sandbox Code Playgroud)
将令牌粘贴到 Swagger UI 中的 Api_Key 表单元素中:

小智 9
OpenAPI 3的更新,Swashbuckle.AspNetCore(6.7.1)完整文章地址: https: //codeburst.io/api-security-in-swagger-f2afff82fb8e 为swagger添加JWT Bearer授权的代码。将其添加到 Startup.cs 的 ConfigureServices 方法中:
services.AddSwaggerGen(c =>
{
// configure SwaggerDoc and others
// add JWT Authentication
var securityScheme = new OpenApiSecurityScheme
{
Name = "JWT Authentication",
Description = "Enter JWT Bearer token **_only_**",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer", // must be lower case
BearerFormat = "JWT",
Reference = new OpenApiReference
{
Id = JwtBearerDefaults.AuthenticationScheme,
Type = ReferenceType.SecurityScheme
}
};
c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{securityScheme, new string[] { }}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22202 次 |
| 最近记录: |