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

基于Identity Server 5配置JWT认证后如何获取Access Token?

解决Identity Server 5下API获取Access Token失败的问题

问题分析

你的API无法正常获取Access Token,核心问题集中在认证配置和端点授权逻辑上,具体包括:

  • 未指定默认认证方案,导致认证中间件未正确触发
  • TokenValidationParameters配置冲突,手动指定签名密钥干扰了Identity Server的自动密钥获取流程
  • 端点未添加授权要求,未触发完整的认证流程
  • ValidateAudience设置与配置的Audience不匹配

解决方案步骤

1. 指定默认认证方案

修改AddAuthentication方法,明确将JWT Bearer设为默认认证方案:

using Microsoft.AspNetCore.Authentication.JwtBearer;

public static IServiceCollection AddDefaultAuthentication(this IHostApplicationBuilder builder)
{
    // 原代码...
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) // 新增默认方案
            .AddJwtBearer(options =>
            {
                // 原配置内容...
            });
    // 原代码...
}

2. 修正TokenValidationParameters配置

移除手动指定的IssuerSigningKey(Identity Server会自动从发现端点获取签名密钥),并恢复ValidateAudience为true(匹配配置的Audience,确保token针对当前API):

options.TokenValidationParameters = new TokenValidationParameters
{
#if DEBUG
    ValidIssuers = [identityUrl, "https://10.0.2.2:5243"],
#else
    ValidIssuers = [identityUrl],
#endif
    ValidateAudience = true, // 改为true,验证token受众
    // 移除该行:IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Constants.SecurityKey)),
    ValidTypes = new[] { "at+jwt" },
};

3. 为端点添加授权要求

只有经过认证的请求才能获取Access Token,需给/token端点添加授权验证:

api.MapGet("/token",  
       async (HttpContext context) => 
             await context.GetTokenAsync("access_token"))
    .RequireAuthorization(); // 新增授权要求

4. 确保中间件顺序正确

在Program.cs中,必须保证认证、授权中间件在端点映射前执行:

var app = builder.Build();

// 中间件顺序不可颠倒
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();

备选获取Token方式

配置正确后,也可通过以下方式获取Access Token:

// 方式1:直接从HttpContext获取
var token = await context.GetTokenAsync("access_token");

// 方式2:从认证结果的属性中获取
var authResult = await context.AuthenticateAsync();
var token = authResult.Properties.GetTokenValue("access_token");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:03:18