I am implementing Swagger UI with my Asp.net WEB Api project, I am using the default System.Web.Http.AuthorizeAttribute, I have registered it in my WebApiConfig.cs in Register method as
config.Filters.Add(new AuthorizeAttribute());
I have implemented Swagger UI as
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "COE.Services.WebAPI");
c.OAuth2("oauth2")
.Description("OAuth2 Implicit Grant")
.Flow("implicit")
.AuthorizationUrl(configurationService.BaseWithTokenUrl)
.Scopes(scopes =>
{
scopes.Add("user_scope", "Access REST API");
});
c.OperationFilter<AssignOAuth2SecurityRequirements>();
})
.EnableSwaggerUi(c =>
{
c.EnableOAuth2Support("COEApi", configurationService.BaseUrl + "swagger/ui/o2c-html", "Swagger");
});
}
public class AssignOAuth2SecurityRequirements : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var toBeAuthorize = apiDescription.GetControllerAndActionAttributes<AuthorizeAttribute>().Any();
var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (toBeAuthorize && !allowAnonymous)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters.Add(new Parameter()
{
name = "Authorization",
@in = "header",
description = "Bearer <token>",
required = true,
type = "string"
});
}
}
}
I have also tried to search the solution on Swashbuckle's Git hub repository but I couldn't find any solution.
I have also come across on opened issue about this on Github