使用Swashbuckle Swagger切换定义时保留授权功能的问题
Solution
Add Security Configuration to OData OpenAPI Document
The OData-generated OpenAPI document (/$openapi) doesn't include your Bearer security definition by default. To add the Authorize button and enable token-based authorization for this definition, customize the OData OpenAPI document during its generation using the DocumentAction option:
app.UseOdataOpenApi(options => { options.DocumentAction = (openApiDoc, odataContext) => { // Add Bearer security definition openApiDoc.Components.SecuritySchemes.Add("Bearer", new OpenApiSecurityScheme { Description = "desc", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "bearer" }); // Add security requirement to enforce token usage openApiDoc.SecurityRequirements.Add(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new List<string>() } }); }; });
How It Works
- This code injects the exact same Bearer security scheme and requirement into the OData-generated document as your first Swagger definition.
- Swagger UI will now display the Authorize button for the "OData raw OpenAPI" definition.
- When you enter your Bearer token in either definition's Authorize modal, Swagger UI automatically applies this token to requests for both definitions (they share the same security scheme ID "Bearer").
Verify the Changes
- Restart your application.
- Navigate to the Swagger UI and switch to the "OData raw OpenAPI" definition—you'll see the Authorize button now.
- Enter your Bearer token and test the OData endpoints; they should no longer return 401 Unauthorized.
内容的提问来源于stack exchange,提问作者sksallaj
相关产品推荐
相关产品推荐

