OpenID Connect is an identity layer built on OAuth 2.0. It lets a client obtain authentication information from an identity provider rather than requiring the application to manage another set of user accounts. For an ASP.NET Core web API, the practical task is to validate the token sent with a request, usually a JSON Web Token (JWT). This reduces the need to store users’ passwords and other personal information locally. section 9.5
A Microsoft-backed API setup has three parts:
- Register the application in an Azure AD tenant, copy its client and tenant IDs into configuration, and expose an API scope. section 9.5.1
- Add Microsoft.AspNetCore.Authentication.JwtBearer; configure JWT bearer authentication and the authentication and authorization middleware; require authorization on the controller. section 9.5
- Configure Swagger UI with OAuth2 security settings and the registered scope so its requests can authenticate. section 9.5.2
Try an authenticated API request
Open Swagger UI and select Authorize. Enter the registered client ID, select the scopes—including the custom API scope—and sign in with the Microsoft account. After granting approval, retry the protected API request: the example changes from a 401 response to a 200 response. section 9.5.2
An OpenID Connect provider publishes a discovery document with configuration such as URLs and available scopes. Swagger UI can use that document, but explicitly configured authorize and token URLs allow the flow settings used here. The Microsoft registration is optional: a company provider, Auth0, Okta, or a self-hosted provider can serve the identity-provider role. section 9.5.2 section 9.5.1
Listing 9.19 Lines to add to Program.cs to configure authentication and the Swagger UI
using Microsoft.OpenApi.Models;
builder.Services.AddControllers(); #1
builder.Services.AddSwaggerGen(options => { #2
var scheme = new OpenApiSecurityScheme() {
Name = "Authorization",
Type = SecuritySchemeType.OAuth2, #3
Scheme = JwtBearerDefaults.AuthenticationScheme, #4
BearerFormat = "JWT", #5
In = ParameterLocation.Header, #6
Flows = new OpenApiOAuthFlows {
Implicit = MsAuthHelper.GetImplicitFlow( #7
config,
"somescope".AddScopePrefix(config)) #8
}
};
options.AddSecurityDefinition("token", scheme); #9
options.AddSecurityRequirement(
new OpenApiSecurityRequirement { { #10
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "token", #11
}
},
Array.Empty<string>()
}
});
});
builder.Services
.AddAuthentication(
JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => options.ValidateMs(config)); #12
var app = builder.Build(); #13
The Program.cs listing shows how the Swagger UI security definition connects an OAuth2 flow and scope to JWT bearer authentication. section 9.5.2












