Do not forget the basic principles of Open ID Connect and OAuth2. When you want to protect an API with OAuth2 and Azure AD, you must pass an access token that will be validated. So if you want to test with SwaggerUI, on accessing the API portion, SwaggerUI must be configured to authenticate, acquire an access token, and pass it to the API.

Before we get started, ensure you create two app registrations in Azure AD, one for the client i.e. SwaggerUI as a Single Page Application, and one for the API, i.e. your Swagger API.

Ensure on the API app registration, you have configured to expose an API..

So to configure SwaggerUI…

builder.Services.AddSwaggerGen(options =>

    var AzureAdMetadata = builder.Configuration["SwaggerClient:Metadata"]!;

    options.AddSecurityDefinition("Oauth2", new OpenApiSecurityScheme
        In = ParameterLocation.Header,
        //Description = "Please enter a valid token",
        Name = "Authorization",
        Type = SecuritySchemeType.OpenIdConnect,
        BearerFormat = "JWT",
        Scheme = "Bearer",
        OpenIdConnectUrl = new Uri(AzureAdMetadata),

    options.AddSecurityRequirement(new OpenApiSecurityRequirement
            new OpenApiSecurityScheme
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Oauth2" }
            new string[]{}

// ...

app.UseSwaggerUI(options =>
    options.OAuthScopes(new[] { builder.Configuration["SwaggerClient:Scopes"], "openid", "profile", "offline_access" });
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
    //options.RoutePrefix = string.Empty;

Don’t forget to add your redirect URI “https://YOUR_APP_PATH/oauth2-redirect.html” as a single page application reply address on the client application registration.

Your appsettings.json will look something like this…

The following identity settings need to be configured
before the project can be successfully executed.
For more info see
  "SwaggerAPI": {
    "Instance": "",
    "Domain": "",
    "TenantId": "YOUR_TENANT_ID",
    "ClientId": "YOUR_API_APP_ID",
  "SwaggerClient": {
    "Metadata": "",
    "ClientId": "YOUR_CLIENT_APP_ID",
    "RedirectUrl": "https://YOUR_APP_PATH/oauth2-redirect.html",

And your authentication code if using Microsoft Identity Web would look like this…

builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration, "SwaggerAPI");

When all said and done, after launching your Swagger app, you should now see an Authorize button at the top of your page. This will load the “Swagger Client” to acquire the access token. Then, when you test your API calls from the Swagger UI, it will automatically pass the access token.

Leave a Comment