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

IdentityServer4如何创建身份令牌?获取id token的端点疑问

关于IdentityServer4获取ID Token的问题解答

嘿,我来帮你理清这个困惑!其实获取ID Token和Access Token用的是同一个Token端点(就是你代码里的discoResponse.TokenEndpoint),问题大概率出在请求参数的配置上,而不是端点选错了。

核心问题:你需要在请求中包含openid Scope

ID Token是OpenID Connect(OIDC)协议的产物,IdentityServer4只会在你明确请求openid这个scope的时候才会返回它。如果你的原有请求只加了API相关的scope,那自然拿不到ID Token。

修正后的代码示例

我把你的代码补全并修正关键参数,你可以参考:

var disco = new DiscoveryClient("http://localhost:55678");
var discoResponse = await disco.GetAsync();
if (discoResponse.IsError) 
{
    Console.WriteLine(discoResponse.Error);
    return null;
}

// 初始化Token客户端,替换成你的客户端ID和密钥
var tokenClient = new TokenClient(
    discoResponse.TokenEndpoint,
    "mvc_client",
    "your_client_secret");

// 重点:Scope必须包含`openid`,还可以附加profile、email等OIDC标准scope,或者你的API scope
var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(
    "your_username", 
    "your_password", 
    "openid profile api1");

if (tokenResponse.IsError)
{
    // 这里一定要看错误信息,IdentityServer会告诉你具体哪里错了
    Console.WriteLine(tokenResponse.Error);
    return null;
}

// 现在就能拿到ID Token了
Console.WriteLine("ID Token: " + tokenResponse.IdentityToken);
Console.WriteLine("Access Token: " + tokenResponse.AccessToken);

额外要检查的配置

  1. 客户端AllowedScopes配置:确保你在IdentityServer的客户端配置里,已经把openid加入到AllowedScopes中,否则服务器会拒绝返回ID Token:
new Client
{
    ClientId = "mvc_client",
    ClientSecrets = { new Secret("your_client_secret".Sha256()) },
    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, // 或者你用的其他授权类型
    AllowedScopes = { "openid", "profile", "api1" } // 必须包含openid
}
  1. 授权类型适配:如果你用的是Authorization Code Flow(更推荐的前端/后端应用模式),那在跳转授权页面的时候就要带上openid scope,之后用授权码交换Token时,服务器也会自动返回ID Token。

排查小技巧

如果还是拿不到ID Token,先打印tokenResponse.Error的内容——IdentityServer的错误信息非常直白,会告诉你是scope不允许、客户端配置错误,还是参数缺失,能帮你快速定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:19:32