Swashbuckle.SwaggerUi with OpenIddict and Bearer Tokens

Authorize Button

It addition to its basic setup, Swashbuckle for ASP.NET Core needs an OAuth2Scheme that tells it how to obtain an access token.

services.AddSwaggerGen(options =>  
        "OpenID Connect", 
        new OAuth2Scheme
            Type = "oauth2",
            Flow = "implicit",
            AuthorizationUrl = "/connect/authorize"

The above is in the context of the following OpenIddict configuration, which enables the implicit flow with an authorization endpoint...


...and adds the default client from the default swagger/ui/index.html file.

dbContext.Applications.Add(new OpenIddictApplication  
    ClientId = "your-client-id",
    DisplayName = "your-app-name",
    LogoutRedirectUri = $"http://localhost:53817/swagger/ui/o2c.html",
    RedirectUri = $"http://localhost:53817/swagger/ui/o2c.html",
    Type = OpenIddictConstants.ClientTypes.Public

Now our Swagger UI will have a lovely Authorize button. Clicking on it will initiate the implicit flow. Once it has an access token, Swagger UI will automatically include that token in the Authorization: Bearer access_token header.