gpt4 book ai didi

swagger - 在 ASP.NET Core 2.2 中使用 nswag 设置承载 token

转载 作者:行者123 更新时间:2023-12-03 16:03:25 24 4
gpt4 key购买 nike

我有一个 ASP.NET Core 2.2 Web Api,我用 nswag 添加了 swagger 支持。
Web api 使用生成访问 token 的本地 IdentityServer4 进行保护。

我找到了添加授权按钮和表单并在标题中设置不记名 token 的代码。它有效!

public void ConfigureServices(IServiceCollection services)
{
//...
services.AddSwaggerDocument(config =>
{
config.DocumentName = "OpenAPI 2";
config.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT Token"));
config.AddSecurity("JWT Token", Enumerable.Empty<string>(),
new OpenApiSecurityScheme()
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
In = OpenApiSecurityApiKeyLocation.Header,
Description = "Copy this into the value field: Bearer {token}"
}
);
});
//...
}

Swagger 页面中的按钮

enter image description here

不记名 token 的复制/粘贴表格

enter image description here

我正在寻找一种无需复制/粘贴即可自动化流程和设置访问 token 的方法。

是否可以设置 nswag 来执行此操作?

最佳答案

您可以在生成器和 Swagger UI 中启用身份验证。要在 web api 中添加 OAuth2 身份验证(OpenAPI 3):

services.AddOpenApiDocument(document =>
{
document.AddSecurity("bearer", Enumerable.Empty<string>(), new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.OAuth2,
Description = "My Authentication",
Flow = OpenApiOAuth2Flow.Implicit,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
Scopes = new Dictionary<string, string>
{
{"api1", "My API"}

},
TokenUrl = "http://localhost:5000/connect/token",
AuthorizationUrl = "http://localhost:5000/connect/authorize",

},
}
});

document.OperationProcessors.Add(
new AspNetCoreOperationSecurityScopeProcessor("bearer"));
}
);

配置 :
app.UseOpenApi();
app.UseSwaggerUi3(settings =>
{
settings.OAuth2Client = new OAuth2ClientSettings
{
ClientId = "demo_api_swagger",

AppName = "Demo API - Swagger",

};
});

在身份服务器 4 中,注册 api :
public static IEnumerable<ApiResource> GetApis()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}

和客户:
new Client {
ClientId = "demo_api_swagger",
ClientName = "Swagger UI for demo_api",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = {"https://localhost:44304/swagger/oauth2-redirect.html"},
AllowedScopes = { "api1" }
},

点击后 Authorize UI 中的按钮,您可以使用 IDS4 进行身份验证并获取 api 的访问 token ,然后在发出 api 请求时 token 将自动附加到授权请求 header 。

关于swagger - 在 ASP.NET Core 2.2 中使用 nswag 设置承载 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59022329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com