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

不问归期 提交于 2019-12-11 15:29:43

问题


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.


回答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.




回答2:


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);
 }


来源:https://stackoverflow.com/questions/47976035/swagger-ui-oauth-password-flow-retrieve-and-add-token-to-authorized-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!