Reputation: 119
I have just started using Swagger UI for ASP.Net API web project in MVC. Most of the parts I understood properly except the authentication.
I am using OAuth ASP.Net Identity. following are my settings:
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>
Upon authorizing the /Token request from APP page.
But when I try to access values endpoint it throws an error.
and the reason for that is the request is missing the Bearer Token that should go in headers
I have already tried few solutions but was not able to resolve it.
Thanks in advance.
Upvotes: 0
Views: 3529
Reputation: 645
You could also check on both the ActionDescriptor and the ControllerDescriptor like this. It will prevent you from putting Authorize attributes on all your controller methods.
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);
}
Upvotes: 0
Reputation: 11
I have also tried this recently,you have to put [Authorize] attribute in method level but not at controller level then it will works and sends Bearer token in each request.
Upvotes: 1