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

ASP.NET Core 6 MVC/API:外部客户端Bearer Token无法访问API控制器求助

ASP.NET Core 6 Web API 外部Bearer令牌调用失败问题解决

1. 确保认证中间件同时支持Cookie和Bearer令牌

你的应用当前仅配置了OpenID Connect(基于Cookie)认证,外部客户端使用Bearer令牌调用API时,需要额外启用JWT Bearer认证。在Program.cs中补充配置:

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    // 保留你已有的OpenID Connect配置,如Authority、ClientId、ClientSecret等
})
.AddJwtBearer(options =>
{
    options.Authority = "你的身份认证服务器地址"; // 与OpenID Connect的Authority一致
    options.Audience = "你的Web API的受众标识"; // 需与令牌中的aud字段匹配
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true
    };
});

同时保证中间件管道顺序正确:

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapRazorPages();

2. 修正API控制器的授权属性

避免API控制器的[Authorize]属性仅限定Cookie认证,需同时允许Bearer方案:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;

[Authorize(AuthenticationSchemes = $"{CookieAuthenticationDefaults.AuthenticationScheme},{JwtBearerDefaults.AuthenticationScheme}")]
[ApiController]
[Route("api/[controller]")]
public class YourApiController : ControllerBase
{
    // 控制器逻辑
}

3. 验证Bearer令牌的有效性

  • 确认外部客户端获取的令牌,其aud(受众)字段与你API配置的Audience完全匹配
  • 检查令牌的iss(颁发者)与你配置的Authority一致,且令牌未过期
  • 使用本地JWT解析工具验证签名是否合法,确保API能正确识别身份服务器的签名密钥

4. 检查请求头格式

外部客户端发送请求时,必须在请求头中正确携带令牌,格式为:

Authorization: Bearer {你的令牌内容}

注意Bearer与令牌之间有一个空格,且令牌无多余空格或特殊字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:13:20