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

在.NET 6中集成Google OpenID与Swagger的身份认证问题

解决方案

1. 核心问题:缺少OpenID必填配置

要通过Google OpenID获取id_token,必须满足两个关键前提:

  • 授权请求的response_type必须包含id_token(隐式流需指定id_token token,同时获取id_token和access_token)
  • 必须添加openid权限范围(这是OpenID Connect的核心标识,无此范围Google不会返回id_token)

2. 修改Swagger配置

更新你的AddSecurityDefinition配置,补充openid scope,并通过扩展指定授权请求的response_type:

services.AddSwaggerGen(c =>
{
    c.AddSecurityRequirement(new OpenApiSecurityRequirement() {  
        {  
            new OpenApiSecurityScheme {  
                Reference = new OpenApiReference {  
                    Type = ReferenceType.SecurityScheme,  
                    Id = "oauth2"  
                },  
                Scheme = "oauth2",  
                Name = "authorization",  
                In = ParameterLocation.Header  
            },  
            new List<string> { "openid", "https://www.googleapis.com/auth/userinfo.email" }  
        }  
    });   
    
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            Implicit= new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri("https://accounts.google.com/o/oauth2/auth"),
                // 隐式流无需TokenUrl,可直接移除
                Scopes = new Dictionary<string, string>
                {
                    { "openid", "OpenID Connect核心范围" },
                    { "https://www.googleapis.com/auth/userinfo.email", "获取用户邮箱" }
                },
                // 扩展配置指定response_type和使用id_token作为请求令牌
                Extensions = new Dictionary<string, IOpenApiExtension>
                {
                    { "x-oauth2-response-type", new OpenApiString("id_token token") },
                    { "x-tokenName", new OpenApiString("id_token") }
                }
            }
        }
    });
});

3. 后端验证id_token

当Swagger请求携带id_token后,需在.NET后端配置JWT验证来解析用户信息:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://accounts.google.com";
        options.Audience = "你的Google OAuth客户端ID"; // 替换为实际客户端ID
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "https://accounts.google.com",
            ValidateAudience = true,
            ValidateLifetime = true,
            NameClaimType = "email" // 从JWT的email字段提取用户身份信息
        };
    });

4. 验证效果

重启应用后在Swagger中发起授权:

  • 授权请求会自动携带response_type=id_token token和openid scope
  • 登录完成后,Swagger会将id_token放入请求头的Authorization字段
  • 后端可通过User.FindFirstValue(ClaimTypes.Email)直接获取用户邮箱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:54:40