Swagger UI - Oauth password flow, retrieve and add token to authorized requests

Jitender Sharma Source

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.

Successful authentication and I do get the access_token as well when I look in console

But when I try to access values endpoint it throws an error.

enter image description here

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.

c#asp.net-web-apioauthswaggerswagger-ui

Answers

answered 4 months ago PaWaN #1

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.

comments powered by Disqus