You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

  1. Restart your application.
  2. Navigate to the Swagger UI and switch to the "OData raw OpenAPI" definition—you'll see the Authorize button now.
  3. Enter your Bearer token and test the OData endpoints; they should no longer return 401 Unauthorized.

内容的提问来源于stack exchange,提问作者sksallaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:55:21