RicoSuter/NSwag

Swagger UI: Using implicit flow for OAuth2/OpenIdConnect

Open

#1,539 opened on Aug 15, 2018

View on GitHub
 (15 comments) (7 reactions) (0 assignees)C# (1,189 forks)batch import
help wantedproject: wikitype: bug

Repository metrics

Stars
 (6,291 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

After some trial and error I've managed to configure the OAuth2 authorization against AWS Cognito in the Swagger UI client.

Ideally, I would have used the OpenIdConnectUrl configuration in the SwaggerSecuritySchemeType.OpenIdConnect settings. Which seemed to work to an extent, as it was correctly downloading the configuration from the endpoint published by AWS Cognito and then redirecting to the login page.

However, Swagger UI was not receiving the configuration for the implicit flow, so the process was failing due to the missing response_type=token parameter in the query string.

As a workaround, the following configuration works when using OAuth2 config for Cognito. I'm leaving it here so that it can be found by others trying to use a similar setup.

// Note: This is a custom POCO used to retrieve the settings
var swaggerOptions = app.ApplicationServices.GetService<IOptions<SwaggerUIOptions>>()?.Value;

app.UseSwaggerUi3WithApiExplorer(settings =>
            {
                settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT token"));

                settings.OAuth2Client = new OAuth2ClientSettings()
                {
                    AppName = "MyDemoApp",
                    ClientId = swaggerOptions.SwaggerClientId
                };

                settings.GeneratorSettings.DocumentProcessors.Add(new SecurityDefinitionAppender("JWT token",
                    new SwaggerSecurityScheme
                    {
                        Type = SwaggerSecuritySchemeType.OAuth2,
                        Flow = SwaggerOAuth2Flow.Implicit,
                        Flows = new OpenApiOAuthFlows() {
                            Implicit = new OpenApiOAuthFlow()
                            {
                                Scopes = new Dictionary<string, string> { { "openid", "User Profile" } },
                                AuthorizationUrl = swaggerOptions.AuthorizationUrl,
                                TokenUrl = swaggerOptions.TokenUrl
                            }
                        }
                    }));
                });

Contributor guide