Swashbuckle OAuth2 Authorization with Client Credential Flow

I use Swashbuckle to document WebAPI controllers. I also use OAuth2 with a client credential stream. Therefore, for authorization, I need to pass client_id and client_secret .

I have the 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 hardcoded (clientIdValue, clientSecretValue). How can I add the ability to enter these values ​​by the user in this dialog box? Can anybody help me?

enter image description here

Please let me know if I need to send AssignOAuthSecurityRequirements code as AssignOAuthSecurityRequirements . Thanks to everyone in advance.

+5
source share
1 answer

Not sure exactly what went wrong in your code, possibly missing scope definitions.

I have successfully mastered ASP.NET Core and the current version of Swashbuckle.AspNetCore ( https://github.com/domaindrivendev/Swashbuckle.AspNetCore )

The client credential stream is called an “application,” so in the 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 should point to a valid Token endpoint compatible with OAuth 2.0 (checkout http://docs.identityserver.io/en/release/endpoints/token.html for an example of how the endpoint should behave / looks like) . Both absolute and relative URLs worked in my tests.

After that, the authorization dialog should look like this:

Authorize popup

  • Please note that you need to select at least one scope before the login button actually sends anything (the oauth component must be modified to add an IMHO disclaimer).

The SwaggerUI section does not require additional configuration.

0
source

Source: https://habr.com/ru/post/1264944/


All Articles