我刚刚开始在MVC中使用Swagger UI for ASP.Net API web项目。我认识的大多数部分都是正确的,除了身份验证。
我正在使用OAuth ASP.Net Identity。以下是我的设置:
SwaggerConfig.cs
c.OAuth2("oauth2")
.Description("OAuth2 Implicit Grant")
.Flow("password")
.AuthorizationUrl("/api/Account/ExternalLogin")
.TokenUrl("/Token")
.Scopes(scopes =>
{
scopes.Add("values:read", "Read access to protected resources");
scopes.Add("values:write", "Write access to protected resources");
});
c.OperationFilter<AssignOAuth2SecurityRequirements>();
AssignOAuth2SecurityRequirements.cs
internal class AssignOAuth2SecurityRequirements : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var authorizeAttributes = apiDescription.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();
if (!authorizeAttributes.Any())
return;
if (operation.security == null)
operation.security = new List<IDictionary<string, IEnumerable<string>>>();
var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", Enumerable.Empty<string>() }
};
operation.security.Add(oAuthRequirements);
}
}
的index.html
<script>
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "http://localhost:17527/swagger/docs/v1",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
</script>
在从APP页面授权/令牌请求时。
但是当我尝试访问值端点时,它会抛出错误。
原因是请求缺少应该进入标头的承载令牌
我已经尝试了一些解决方案,但无法解决它。
提前致谢。
我最近也试过这个,你必须把[Authorize]属性放在方法级别而不是在控制器级别然后它将工作并在每个请求中发送Bearer令牌。
您还可以像这样检查ActionDescriptor和ControllerDescriptor。它将阻止您在所有控制器方法上放置Authorize属性。
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var authorizeAttributes = apiDescription.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>().Any()
? apiDescription.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>()
: apiDescription.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AuthorizeAttribute>();
if (!authorizeAttributes.Any())
return;
if (operation.security == null)
operation.security = new List<IDictionary<string, IEnumerable<string>>>();
var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", Enumerable.Empty<string>() }
};
operation.security.Add(oAuthRequirements);
}