Azure Active Directory 登录返回未找到签名密钥

时间:2020-12-30 10:26:27

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

我已经使用 Azure AD 为我的 ASP.NET Core 3.0 Web API 实现了身份验证。当我使用 [Authorize] 属性时,我收到带有消息的 http 401 错误响应

<块引用>

Bearer error="invalid_token", error_description="未找到签名密钥"

我目前在 ConfigureService() 中的 Startup.cs 看起来像这样:

options.AddSecurityDefinition("oauth", new OpenApiSecurityScheme()
{
    Type = SecuritySchemeType.OAuth2,
    Flows = new OpenApiOAuthFlows()
    {
        Implicit = new OpenApiOAuthFlow()
        {
            TokenUrl = new Uri($"https://login.microsoftonline.com/<mytenantid>/oauth2/v2.0/token"),
            AuthorizationUrl = new Uri($"https://login.microsoftonline.com/TenantId/oauth2/v2.0/authorize", UriKind.RelativeOrAbsolute),
            Scopes = { { "api://<myappid>/user_impersonation", "user_impersonation" } }
        }
    }
});

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = $"https://login.microsoftonline.com/<mytenantid>/v2.0";
        o.Audience = "<myappid>";
        o.TokenValidationParameters.ValidAudiences = new string[] { "<myappid>", $"api://<myappid>" };
    });                

options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                 Id = "oauth"
                            },
            Scheme = "oauth2",
            Name = "Bearer",
            In = ParameterLocation.Header,
        },
        new List<string>()
    }
});

如果我遗漏了什么,请告诉我

1 个答案:

答案 0 :(得分:0)

我之前回答过很多类似的问题。根据您的问题,您公开了受 Azure 保护的 web api。接下来,您需要创建一个客户端应用程序,并使用该客户端应用程序调用 api 应用程序。

通常 401 错误意味着您的令牌的受众与您的 api 不匹配。使用token调用api时,会收到401未授权错误。访问令牌是根据受众发布的,因此您必须确保在请求令牌时将 scope 设置为您的 api。当然你也可以解析token,检查aud声明,确定是你要调用的api。

我用auth code flow为你做一个简单的演示:

首先暴露api应用的api,添加客户端应用。 enter image description here

接下来,在“API 权限”下,授予您的前端应用程序访问后端 API 应用程序的权限:

  • 在“API 权限”下点击“添加权限”,然后点击“我的 API”标签。
  • 找到您的后端应用程序并选择适当的范围。
  • 点击“添加权限”。
  • 为您的 API 授予管理员许可。

enter image description here

获取令牌: enter image description here

解析token:

enter image description here