Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swashbuckle OAuth2 Authorization with Client Credentials Flow

I use Swashbuckle to documentation of WebAPI controllers. Also I use OAuth2 with Client Credentials Flow. So to authorize I need to pass client_id and client_secret.

I have following code:

config.EnableSwagger(c => {
    c.SingleApiVersion("v1", "My API");
    c.OAuth2("oauth2")
        .Flow("application")
        .TokenUrl("/oauth2/token");
    c.OperationFilter<AssignOAuthSecurityRequirements>();
})
.EnableSwaggerUi(c => {
    c.EnableOAuth2Support(clientId: "clientIdValue", clientSecret:"clientSecretValue", "", "");
    c.CustomAsset("index", Assembly.GetExecutingAssembly(), "WebAPI.Swagger.UI.index.html");
});

Authorization works fine but my client_id and client_secret values are hardcoded(clientIdValue, clientSecretValue). How can I add possibility to input that values by user in this dialog? Can anyone help me?

enter image description here

Please let me know if I need to post code of AssignOAuthSecurityRequirements too. Thanks all in advance

like image 750
Robert N. Dean Avatar asked Mar 02 '17 14:03

Robert N. Dean


1 Answers

Not sure exactly what went wrong in your code, maybe the lack of scope definitions.

I've done it successfully with ASP.NET Core and the current version of Swashbuckle.AspNetCore (https://github.com/domaindrivendev/Swashbuckle.AspNetCore)

The client credentials flow is referred to as "application" so, in your Startup.cs file, you need to configure Swagger as follows:

        services.AddSwaggerGen(c => {

            //other configs...

            c.AddSecurityDefinition("oauth2", new OAuth2Scheme {
                Type = "oauth2",
                Flow = "application",
                TokenUrl = "<token_endpoint_url>",
                Scopes = new Dictionary<string, string>
                {
                    { "first-scope", "First scope description" },
                    { "second-scope", "Second scope description" }
                    //define as many scopes as you want...
                }
            });
        });

The TokenUrl parameter must point to a valid OAuth 2.0 compliant Token endpoint (checkout http://docs.identityserver.io/en/release/endpoints/token.html for a sample on how the endpoint should behave/look like). Both absolute and relative URLs worked in my tests.

After that, the authorization dialog should look like bellow:

Authorize popup

  • Please note, that you need to select at least one scope before the authorize button actually submits anything (the oauth component should be changed to add a disclaimer IMHO).

No additional configuration was required in the SwaggerUI section.

like image 106
André Lourenço Avatar answered Sep 17 '22 19:09

André Lourenço