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

如何配置Swagger对接IdentityServer获取Bearer令牌调用授权API?

配置Swagger与IdentityServer对接实现Bearer令牌认证

一、API项目中配置Swagger支持OAuth2.0授权码流程

先确保API项目已引用Swashbuckle.AspNetCore和Swashbuckle.AspNetCore.SwaggerUI NuGet包,再在Program.cs中做以下配置:

  1. 添加Swagger安全定义与要求
builder.Services.AddSwaggerGen(c =>
{
    // 定义Bearer令牌认证方案
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            AuthorizationCode = new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri("https://localhost:5001/connect/authorize"), // 替换为你的IdentityServer授权端点
                TokenUrl = new Uri("https://localhost:5001/connect/token"), // 替换为你的IdentityServer令牌端点
                Scopes = new Dictionary<string, string>
                {
                    { "your_api_scope", "你的API资源权限名称" } // 替换为你API对应的scope
                }
            }
        }
    });

    // 要求所有接口使用该认证方案
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "oauth2"
                }
            },
            new[] { "your_api_scope" }
        }
    });
});
  1. 配置Swagger UI的OAuth2客户端信息
app.UseSwaggerUI(c =>
{
    c.OAuthClientId("swagger_client"); // 对应IdentityServer中配置的客户端ID
    c.OAuthClientSecret("swagger_secret"); // 对应IdentityServer中配置的客户端密钥(按需设置)
    c.OAuthAppName("Swagger API测试");
    c.OAuthUsePkce(); // 启用PKCE提升安全性
});

二、IdentityServer中配置Swagger专用客户端

在IdentityServer的客户端配置类(比如Config.cs的GetClients方法)中,新增Swagger专属客户端:

public static IEnumerable<Client> GetClients()
{
    return new List<Client>
    {
        // 其他客户端配置...
        new Client
        {
            ClientId = "swagger_client",
            ClientName = "Swagger测试客户端",
            ClientSecrets = { new Secret("swagger_secret".Sha256()) },

            AllowedGrantTypes = GrantTypes.Code,
            RequirePkce = true,
            RedirectUris = { "https://localhost:7001/swagger/oauth2-redirect.html" }, // 替换为你的API Swagger回调地址
            PostLogoutRedirectUris = { "https://localhost:7001/swagger/index.html" },
            AllowedScopes = { "openid", "profile", "your_api_scope" }, // 包含openid、profile及你的API scope
            AllowAccessTokensViaBrowser = true,
            RequireClientSecret = false // 用PKCE时可省略客户端密钥,按需调整
        }
    };
}

三、验证流程

  1. 依次启动IdentityServer、API项目
  2. 打开API的Swagger页面(如https://localhost:7001/swagger)
  3. 点击右上角Authorize按钮,勾选配置的scope后点击Authorize
  4. 页面跳转至IdentityServer登录页,输入合法账号密码完成认证
  5. 认证成功后自动回调回Swagger,此时Swagger已获取Bearer令牌
  6. 调用API接口时,Swagger会自动在请求头携带Authorization: Bearer {token},即可正常访问带[Authorize]属性的接口

关键说明

不需要在API项目中单独编写令牌生成端点,直接复用IdentityServer的授权、令牌端点即可,既能保证认证逻辑统一,也避免重复开发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:22:39