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

Blazor ASP.NET Core 6.0托管应用:.AddOpenIdConnect()配置后无法调用API

问题分析与解决方案

你的核心问题是当前认证配置仅支持基于Cookie的会话授权(适配Blazor应用的用户交互),但Postman调用API需要JWT Bearer令牌验证;同时配置JWT Bearer时未正确从身份提供商获取验证密钥,导致403错误。以下是具体修正步骤:

1. 调整认证配置,同时支持Cookie会话与JWT Bearer验证

修改Program.cs中的认证配置,同时添加JWT Bearer支持,并适配PKCE流的OIDC设置:

builder.Services.AddAuthentication(options =>
{
    // 默认用Cookie处理Blazor应用的用户会话
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
// 适配PKCE流的OIDC配置
.AddOpenIdConnect(options =>
{
    options.Authority = builder.Configuration["Authentication:Authority"];
    options.ClientId = builder.Configuration["Authentication:ClientId"];
    // PKCE流属于公共客户端,无需ClientSecret,移除该行
    // options.ClientSecret = builder.Configuration["Authentication:ClientSecret"];
    options.ResponseType = OpenIdConnectResponseType.Code;
    options.SaveTokens = true;
    options.GetClaimsFromUserInfoEndpoint = true;
    // 显式开启PKCE支持
    options.UsePkce = true;
    // 添加API访问所需的权限范围
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add(builder.Configuration["Authentication:ApiScope"]);
})
// 添加JWT Bearer验证,用于API请求
.AddJwtBearer(options =>
{
    options.Authority = builder.Configuration["Authentication:Authority"];
    options.Audience = builder.Configuration["Authentication:ApiAudience"]; // API的受众标识符
    // 自动从身份提供商的JWKS端点获取验证密钥,无需手动配置自签名密钥
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true
    };
});

// 配置授权策略,指定API使用Bearer验证
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ApiBearer", policy =>
    {
        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
        policy.RequireAuthenticatedUser();
    });
});

2. 给API控制器绑定Bearer授权策略

在API控制器或具体Action上添加授权特性,指定使用JWT Bearer验证:

[ApiController]
[Route("api/[controller]")]
[Authorize(Policy = "ApiBearer")]
public class SampleController : ControllerBase
{
    // 你的API方法逻辑
}

3. Postman请求的正确操作

  • 通过PKCE流获取Access Token(注意不是ID Token,除非身份提供商配置ID Token包含API受众)
  • 在Postman的请求头中添加:Authorization: Bearer <你的Access Token>
  • 确保获取令牌时请求的scope包含API的访问范围,且令牌的aud(受众)与AddJwtBearer中配置的Audience完全一致

关键注意事项

  • PKCE流是为公共客户端设计的,绝对不能保留ClientSecret配置
  • JWT Bearer验证无需手动配置自签名密钥,ASP.NET Core会自动从身份提供商的/.well-known/openid-configuration/jwks端点获取公钥用于令牌签名验证
  • 如果是Blazor WebAssembly托管应用,客户端(WASM)的认证配置也需要同步适配PKCE流,服务器端仅负责API的JWT验证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:27:34