承载错误-invalid_token-找不到签名密钥

时间:2019-10-25 18:11:08

标签: c# angular asp.net-core jwt azure-active-directory

我有一个与.Net Core 2.2 API后端接口的Angular 7应用程序。这是与Azure Active Directory的接口。

在Angular 7方面,它已通过AAD进行了正确的身份验证,并且我得到了jwt.io上验证的有效JWT。

在.Net Core API方面,我创建了一个简单的测试API,上面带有[Authorize]

当我从Angular调用此方法时,添加Bearer令牌后,我得到了(如Chrome调试工具的“网络”标签中的“标题”所示):

  

WWW-Authenticate:承载错误=“ invalid_token”,error_description =“ The   找不到签名密钥”

使用 HTTP / 1.1 401未经授权

简单的测试API是:

    [Route("Secure")]
    [Authorize]
    public IActionResult Secure() => Ok("Secure works");

Angular调用代码也很简单:

    let params : any = {
        responseType: 'text',
        headers: new HttpHeaders({
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        })
    }

    this.http
        .get("https://localhost:5001/api/azureauth/secure", params)
        .subscribe(
            data => { },
            error => { console.error(error); }
        );

如果我删除了[Authorize]属性,并且只是从Angular中将其称为标准GET请求,那么它就可以正常工作。

我的Startup.cs包含:

        services
            .AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureADBearer(options => this.Configuration.Bind("AzureAd", options));

所有选项均已在appsettings.json中正确设置(例如ClientId,TenantId等),并且options此处已按预期填充。

6 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,因为我缺少授权。.确保授权和api名称正确,现在启动文件中configure services中的这段代码对我有用:

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
                .AddIdentityServerAuthentication( x =>
                {
                    x.Authority = "http://localhost:5000"; //idp address
                    x.RequireHttpsMetadata = false;
                    x.ApiName = "api2"; //api name
                });

答案 1 :(得分:0)

我的Core API使用不同的服务配置(并且可以运行:)):

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                Configuration.Bind("JwtBearer", options);

您确定要传递访问令牌而不是id_token吗?令牌中的aud calim是否与您的API所配置的clientid完全相同?您可能想在选项中添加一些事件,以查看接收的内容以及验证失败的位置。

答案 2 :(得分:0)

  1. 验证为请求jwt令牌而发送的值(例如:grant_type,client_secret,scope,client_id等)
  2. 确保您正在使用适当的令牌。仅此而已!

这是我的错误: 我正在使用邮递员,并请求令牌并将其设置为变量“ Var_Token1”:

pm.environment.set("Var_Token1", pm.response.json().access_token);

但是当我需要在最终请求中使用令牌时,我选择并使用了错误的令牌(Var_Token2):

Authorization: Bearer {{Var_Token2}}

答案 3 :(得分:0)

对我来说,出现这个错误是因为 appsettings.json 中的 URL 不正确。我修复了它,现在工作正常。

答案 4 :(得分:0)

我有一个独特的场景,希望这会对某人有所帮助。

我正在构建一个启用了 Windows 协商身份验证的 API(.NET Core 5.0,从 IIS 运行),并通过不支持协商的 XUnit 使用 CustomWebApplicationFactory (see documentation for CustomWebApplicationFactory) 对 API 进行单元测试身份验证。

出于单元测试的目的,我告诉 CustomWebApplicationFactory 使用“UnitTest”环境(ASPNETCORE_ENVIRONMENT 变量)并专门将逻辑编码到我的应用程序 Startup.cs 文件中,以便仅为“UnitTest”环境。

我遇到此错误是因为我的 Startup.cs 配置没有我用来创建令牌的签名密钥(下面的 IssuerSigningKey)。

if (_env.IsEnvironment("UnitTest"))
{
  // for unit testing, use a mocked up JWT auth, so claims can be overridden
  // for testing specific authentication scenarios
  services.AddAuthentication()
    .AddJwtBearer("UnitTestAuth", opt =>
    {
      opt.Audience = "api://local-unit-test";
      opt.RequireHttpsMetadata = false;
      opt.TokenValidationParameters = new TokenValidationParameters()
      {
        ClockSkew = TokenValidationParameters.DefaultClockSkew,
        ValidateAudience = true,
        ValidateIssuer = true,
        ValidateIssuerSigningKey = true,
        ValidAudience = "api://local-unit-test",
        ValidIssuer = "unit-test",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("abcdefghijklmnopqrstuvwxyz123456"))
      };
    });
} else {
  // Negotiate configuration here...
}

无论 ValidateIssuerSigningKeytrue 还是 false,我仍然收到“invalid_token”401 响应,与 OP 相同。我什至尝试指定一个自定义 IssuerSigningKeyValidator 委托来始终覆盖结果,但也没有运气。

<块引用>

WWW-Authenticate: Bearer error="invalid_token", error_description="未找到签名密钥"

当我将 IssuerSigningKey 添加到 TokenValidationParameters 对象(当然匹配我在单元测试中生成令牌时使用的密钥)时,一切都按预期工作。

答案 5 :(得分:-1)

我遇到了这个问题,这是由于jwtOptions.Authority未在配置中设置造成的。

如果您使用的是

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme,

并且jwtOptions.Authority设置为null或“”,您会收到此错误消息。