SwashBuckle/Swagger - OAuth Resource Owner Password Flow

前端 未结 2 1100
后悔当初
后悔当初 2020-12-18 06:23

I\'m trying to implement swagger into my Asp.Net Web API, and i\'m running into a problem.

I\'m using the password resource owner flow, and i\'m having to add a work

相关标签:
2条回答
  • 2020-12-18 06:56

    I've managed to correct the problem. It was a simple type mismatch that has caused me days of grief.

    In the onComplete.JS, i needed to create a key that matches the key presented in the swagger specification.

    If you examine my code snippets above you will see that i created a key and called it "Authorization". But that does not match the named security definition "oauth2".

    The working code :-

    $('#input_apiKey').change(function () {
        var key = $('#input_apiKey')[0].value;
        var credentials = key.split(':'); 
        $.ajax({
            url: "http://localhost:42291/token",
            type: "post",
            contenttype: 'x-www-form-urlencoded',
            data: "grant_type=password&username=" + credentials[0] + "&password=" + credentials[1],
            success: function (response) {
    
                var bearerToken = "Bearer " + response.access_token;
    
                window.swaggerUi.api.clientAuthorizations.remove('api_key');
    
                var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", bearerToken, "header");
    
                window.swaggerUi.api.clientAuthorizations.add('oauth2', apiKeyAuth);
    
                alert("Login Succesfull!");
    
            },
            error: function (xhr, ajaxoptions, thrownerror) {
                alert("Login failed!");
            }
        });
    });
    

    Just to explain this a bit further, you need to create an implementation of IOperationFilter so that swagger can determine which methods of the api require Authorizaion. When you have configured this correctly, you should see a security definition against each api call in the swagger specification :-

    My implementation of IOperationFilter :-

    public class AssignOAuth2SecurityRequirements : IOperationFilter
        {
            /// <summary>
            /// Apply Security Measures.
            /// </summary>
            /// <param name="operation"></param>
            /// <param name="schemaRegistry"></param>
            /// <param name="apiDescription"></param>
            /// <exception cref="NotImplementedException"></exception>
            public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
            {
                // Determine if the operation has the Authorize attribute
                var authorizeAttributes = apiDescription.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();
    
                if (!authorizeAttributes.Any())
                    return;
    
                // Initialize the operation.security property
                if (operation.security == null)
                    operation.security = new List<IDictionary<string, IEnumerable<string>>>();
    
                // Add the appropriate security definition to the operation
                var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
                {
                    { "oauth2", Enumerable.Empty<string>() }
                };
    
                operation.security.Add(oAuthRequirements);
            }
        }
    
    0 讨论(0)
  • 2020-12-18 06:59

    The authorization mechanism expects that each operation has a security assigned to it. If not present, the header won't be sent. Please share your spec file if you think it's properly assigned

    0 讨论(0)
提交回复
热议问题