不记名令牌未包含在SwaggerUI中
我正在使用AspNet Boilerplate框架。我正在尝试通过AzureAD在我的应用程序中实现身份验证。我正在使用ASP.NET core 3.0并通过 swagger 测试我的应用程序。我看到令牌未包含在标头中。
Startup.cs 的 ConfigureServices() 方法
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
TokenUrl = new Uri(My Token Url),
AuthorizationUrl = new Uri(My Authorization Url),
Scopes = { { "api://357...../user_impersonation", "Access adt-service" } }
}
}
});
Startup.cs 的 Configure() 方法:
{
options.OAuthClientId("22............");
options.OAuthScopeSeparator(" ");
});
如果我遗漏了什么,请告诉我。
回答
当您进行身份验证时,您是否首先收到令牌?在我的回答中,我假设你是。
您没有在代码片段中完全显示这一点,但您必须执行如下操作来配置 Swagger 服务,对吗?
services.AddSwaggerGen(options =>
{
options.SwaggerDoc(...);
options.AddSecurityDefinition(
"oauth",
new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
TokenUrl = new Uri(My Token Url),
AuthorizationUrl = new Uri(My Authorization Url),
Scopes = { { "api://357...../user_impersonation", "Access adt-service" } }
}
}
});
});
如果您是,只需在您的选项中添加一个安全要求,该令牌应已包含在您的请求中:
services.AddSwaggerGen(options =>
{
options.SwaggerDoc(...);
options.AddSecurityDefinition(
"oauth",
new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
TokenUrl = new Uri(My Token Url),
AuthorizationUrl = new Uri(My Authorization Url),
Scopes = { { "api://357...../user_impersonation", "Access adt-service" } }
}
}
});
options.AddSecurityRequirement(
new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "oauth"
}
},
oauthScopes.Keys.ToArray() // array with scopes' keys used above in the security definition
}
});
});
请注意添加options.AddSecurityRequirement. name/id"oauth"只是安全定义的标识名称。
这些片段适用于 .net 5。我相信它们可能适用于 .net core 3