UPDATE 2: If I change my controller Authorize tag from this
[Authorize]
to this
[Authorize(Roles = \"Read\")]
These are the steps which we have done and worked:
c.OAuth2("oauth2") .Description("OAuth2 Implicit Grant") .Flow("implicit") .AuthorizationUrl(swaggerConfigurations["IssuerUri"].ToString()) .Scopes(scopes => { scopes.Add("user_scope", "Access REST API"); });
The attributes are:
II. In the SwaggerConfig file, add the below settings also under the swagger ui configuration section:
c.EnableOAuth2Support(swaggerConfigurations["ClientId"].ToString(), string.Empty, swaggerConfigurations["RedirectUri"].ToString(), "Swagger", " ", new Dictionary { { "resource", GetResources() } });
The method accepts the below parameters:
III. Create a new Operation Filter in the web api project as shown below:
public class CustomOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
string clientId = "clientID";
if (apiDescription != null)
{
var actFilters = apiDescription.ActionDescriptor.GetFilterPipeline();
var allowsAnonymous = actFilters.Select(f => f.Instance).OfType().Any();
if (allowsAnonymous)
{
return; // must be an anonymous method
}
}
if (operation != null)
{
if (operation.security == null)
{
operation.security = new List>>();
}
var authRequirements = new Dictionary>
{
{ "oauth2", new List { clientId } }
};
operation.security.Add(authRequirements);
}
}
}
This class will be used to bind the OAuth scopes to the individual operations
IV. Add the above filter in the swagger config file (see code below)
c.OperationFilter();
V. Configure the Client ID, Secret, Redirect Url and Resource in Security Token Service
VI. In the Web API project, if there is an index.html being used to inject API specific UI fields/styles, then make sure that all the javascript code is kept intact with the Swashbuckle version of the index.html file (as provided in the location - https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/SwaggerUi/CustomAssets/index.html)