You need to enable JavaScript to run this app. 如何为使用客户端凭据流的OpenIddict配置SwaggerGen参数
优惠活动
大模型
产品
解决方案
定价
更多

如何为使用客户端凭据流的OpenIddict配置SwaggerGen参数

解决方案

你遇到的空白模态框问题主要是Swagger安全定义配置错误导致,按以下步骤修改即可:

1. 修正AddSwaggerGen配置

客户端凭据流不需要AuthorizationUrl,且使用OAuth2类型的安全方案适配性更好,修改后的配置如下:

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "PCM", Version = "v1" });
    options.AddSecurityDefinition("OAuth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Description = "OpenIddict 客户端凭据授权",
        Flows = new OpenApiOAuthFlows
        {
            ClientCredentials = new OpenApiOAuthFlow
            {
                // 客户端凭据流仅需要TokenUrl,删除AuthorizationUrl配置
                TokenUrl = new Uri("/connect/token", UriKind.Relative),
                // 此处填写你在OpenIddict中注册的Scope列表,示例如下
                Scopes = new Dictionary<string, string>
                {
                    { "pcm_api", "PCM接口访问权限" }
                }
            }
        }
    });

    // 新增安全要求,让Swagger识别接口需要授权
    options.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "OAuth2"
                }
            },
            Array.Empty<string>()
        }
    });
});

2. 补充SwaggerUI配置

在管道配置部分的UseSwaggerUI中添加客户端默认配置,避免每次手动填写客户端ID和密钥:

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "PCM v1");
    // 替换为你在OpenIddict中注册的客户端ID和密钥
    options.OAuthClientId("your_client_id");
    options.OAuthClientSecret("your_client_secret");
});

3. 验证前置条件

  • 确保你已在OpenIddict中注册了对应的客户端,且启用了客户端凭据流、分配了对应的Scope
  • 确保需要授权的接口添加了[Authorize]特性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 03:24:03