Swashbuckle/Swagger UI OpenID Connect支持:Asp.net Core Web API配置示例项目咨询
Absolutely! I’ve set up OpenID Connect (OIDC) authentication with both Swashbuckle and NSwag in ASP.NET Core Web APIs plenty of times, so let me walk you through step-by-step examples for each tool.
First, you’ll need the necessary NuGet packages:
Install-Package Swashbuckle.AspNetCore Install-Package Swashbuckle.AspNetCore.SwaggerUI
Step 1: Configure OIDC Authentication for Your API
In your Program.cs, set up JWT bearer authentication tied to your OIDC provider (like IdentityServer, Azure AD, or Auth0):
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "https://your-oidc-provider-domain.com"; // e.g., https://demo.identityserver.io options.Audience = "your-api-resource-name"; // The audience identifier for your API options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "https://your-oidc-provider-domain.com", ValidateAudience = true, ValidAudience = "your-api-resource-name", ValidateLifetime = true }; }); builder.Services.AddAuthorization();
Step 2: Configure Swagger to Support OIDC
Next, add Swagger generation and UI configuration, including the OIDC security scheme:
builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "OIDC Protected API", Version = "v1" }); // Define the OIDC security scheme c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { AuthorizationCode = new OpenApiOAuthFlow { AuthorizationUrl = new Uri("https://your-oidc-provider-domain.com/connect/authorize"), TokenUrl = new Uri("https://your-oidc-provider-domain.com/connect/token"), Scopes = new Dictionary<string, string> { { "your-api-resource-name", "Full access to the API" } // Map your API's scope } } } }); // Require OIDC authentication for all API operations c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }, new[] { "your-api-resource-name" } } }); }); // Add middleware to expose Swagger and Swagger UI app.UseAuthentication(); app.UseAuthorization(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "OIDC Protected API v1"); // Configure Swagger UI's OIDC client settings c.OAuthClientId("your-swagger-client-id"); // Client ID registered in your OIDC provider c.OAuthClientSecret("your-swagger-client-secret"); // Only needed if using a confidential client c.OAuthAppName("Swagger UI - API Test"); c.OAuthScopeSeparator(" "); c.OAuthRedirectUrl("https://localhost:5001/swagger/oauth2-redirect.html"); // Must match the redirect URI registered in your OIDC provider });
For NSwag, start by installing the NuGet package:
Install-Package NSwag.AspNetCore
Step 1: Configure OIDC Authentication (Same as Swashbuckle)
Reuse the same authentication setup from the Swashbuckle section above in Program.cs.
Step 2: Configure NSwag for OIDC
Set up the OpenAPI document and Swagger UI with OIDC support:
builder.Services.AddOpenApiDocument(document => { document.Title = "OIDC Protected API"; document.Version = "v1"; // Add OIDC security scheme document.AddSecurity("OAuth2", Enumerable.Empty<string>(), new OpenApiSecurityScheme { Type = OpenApiSecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { AuthorizationCode = new OpenApiOAuthFlow { AuthorizationUrl = "https://your-oidc-provider-domain.com/connect/authorize", TokenUrl = "https://your-oidc-provider-domain.com/connect/token", Scopes = new Dictionary<string, string> { { "your-api-resource-name", "Full access to the API" } } } } }); // Apply the security requirement to all operations document.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("OAuth2")); }); // Add NSwag middleware app.UseAuthentication(); app.UseAuthorization(); app.UseOpenApi(); app.UseSwaggerUi3(settings => { settings.OAuth2Client = new OAuth2ClientSettings { ClientId = "your-swagger-client-id", ClientSecret = "your-swagger-client-secret", // Optional, for confidential clients AppName = "Swagger UI - API Test", ScopeSeparator = " ", RedirectUrl = "https://localhost:5001/swagger/oauth2-redirect.html" // Must match OIDC provider's registered redirect URI }; });
Key Notes
- OIDC Provider Setup: You must register a client for Swagger UI in your OIDC provider. Allow the redirect URL (usually
https://<your-api-url>/swagger/oauth2-redirect.html), set the grant type toAuthorizationCode, and include your API's scope in the allowed scopes. - Testing: Once configured, open Swagger UI, click the "Authorize" button, select your API's scope, and log in with your OIDC provider. You’ll then be able to call protected API endpoints with the authenticated token.
内容的提问来源于stack exchange,提问作者Alexander Torres

