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

IdentityServer4中IntrospectionClient始终返回Unauthorized问题排查

解决IdentityServer4 IntrospectionClient返回Unauthorized的问题

你的问题核心在于ApiResource没有配置验证所需的ApiSecret,同时调用IntrospectionClient时的凭据需要和ApiResource的配置匹配。下面是具体的修复步骤和解释:

1. 给ApiResource添加ApiSecret

在你的Config.GetResources()方法中,当前只定义了ApiResource的名称,没有设置用于introspection端点认证的密钥。IdentityServer4要求调用introspection端点的客户端(这里就是你的API服务)必须提供有效的凭据,而ApiResource的ApiSecret就是这个凭据的核心部分。

修改后的GetResources代码:

public static IEnumerable<ApiResource> GetResources()
{
    return new List<ApiResource> 
    { 
        new ApiResource("api")
        {
            // 添加与IntrospectionClient使用的"secret"对应的ApiSecret
            ApiSecrets = { new Secret("secret".Sha256()) }
        }
    };
}

2. 确认IntrospectionClient的参数正确

你当前的IntrospectionClient调用代码是正确的,使用"api"作为认证用户名(对应ApiResource的Name),"secret"作为密码(对应刚才添加的ApiSecret),这一步不需要修改:

var introspectionClient = new IntrospectionClient(
    dico.IntrospectionEndpoint, 
    "api", 
    "secret");
var vresponse = await introspectionClient.SendAsync(
    new IntrospectionRequest { Token = tokenResult.AccessToken });

额外检查点

  • 确保你获取的tokenResult.AccessToken是有效的:可以先打印令牌内容,用JWT解析工具确认令牌的aud、iss等字段是否正确,是否处于有效期内。
  • 确认IdentityServer的introspection端点已启用:AddIdentityServer默认包含这个端点,你可以访问http://localhost:6001/.well-known/openid-configuration,查看返回结果中是否包含introspection_endpoint字段来验证。

为什么会返回Unauthorized?

当你调用introspection端点时,IdentityServer会先验证调用者的身份:

  1. 它会检查你传入的"api"和"secret"是否匹配某个ApiResource的Name和ApiSecret(或某个Client的ClientId和ClientSecret)。
  2. 因为你之前的ApiResource没有配置ApiSecret,IdentityServer找不到对应的有效凭据,所以直接返回Unauthorized。

添加ApiSecret后,IdentityServer就能识别你的调用请求是合法的,随后才会继续验证令牌的有效性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:46:41