SwashBuckle/Swagger - OAuth Resource Owner Password Flow

前端 未结 2 1105
后悔当初
后悔当初 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
        {
            /// 
            /// Apply Security Measures.
            /// 
            /// 
            /// 
            /// 
            /// 
            public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
            {
                // Determine if the operation has the Authorize attribute
                var authorizeAttributes = apiDescription.ActionDescriptor.GetCustomAttributes();
    
                if (!authorizeAttributes.Any())
                    return;
    
                // Initialize the operation.security property
                if (operation.security == null)
                    operation.security = new List>>();
    
                // Add the appropriate security definition to the operation
                var oAuthRequirements = new Dictionary>
                {
                    { "oauth2", Enumerable.Empty() }
                };
    
                operation.security.Add(oAuthRequirements);
            }
        }
    

提交回复
热议问题