Robert N. Dean
Robert N. Dean

Reputation: 1309

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

Upvotes: 8

Views: 6405

Answers (1)

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.

Upvotes: 1

Related Questions