UseJwtBearerAuthentication 失败:未经授权的令牌和签名无效

UseJwtBearerAuthentication failed: Unauthorized token and The signature is invalid

我有一个网络 api 服务和一个网络客户端应用程序来访问网络 api。两者都在 azure active directory 上注册。 但是,当 Web 客户端应用程序尝试访问 Web api 时,我得到:

ReasonPhrase: 'Unauthorized'
WWW-Authenticate: Bearer error=\"invalid_token\", error_description=\"The signature is invalid

然后我查看了https://jwt.io/上的token,果然显示"invalid signature"。但是,我不知道这里出了什么问题。

这是我检索令牌的方式:

string authority = "https://login.windows.net/tenantid-log-number/oauth2/token";
string clientID = "83adf895-681a-4dd6-9dfb-2a1484dd4188";

string resourceUri = "https://tenant.onmicrosoft.com/webapiservice";
string appKey = "anJxg3N/5dqiHKx+4zwzFB9A6dN5HdqSitdSOpxzVd="; 

ClientCredential clientCredential = new ClientCredential(clientID, appKey);

AuthenticationContext ac = new AuthenticationContext(authority);
Task<AuthenticationResult> authResult = ac.AcquireTokenAsync(resourceUri, clientCredential);
return authResult.Result.AccessToken;

这是我访问网络 api 服务的方式:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://webapiservice.azurewebsites.net/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

HttpResponseMessage response = client.GetAsync("api/values").Result;

Web api 服务验证访问的方式如下:

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
     AutomaticAuthenticate = true,
     AutomaticChallenge = true,

     TokenValidationParameters = new TokenValidationParameters
     {
          ValidateAudience = true,
          ValidAudience = "https://tenant.onmicrosoft.com/webapiservice",
      }
  });

这里有什么问题吗?

谢谢

根据您的配置和代码片段,您似乎正在尝试使用 Azure AD v1 端点为 .Net Core 设置 Web API。

对于使用 Azure AD v1 终结点的 .Net Core,您应该使用 UseJwtBearerAuthentication,如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // ...
    // Other stuff
    // ...

    app.UseJwtBearerAuthentication(
        new JwtBearerOptions
        {
            Authority = string.Format("https://login.microsoftonline.com/{0}/", 
                Tenant),
            Audience = ClientId
        });
}

作为参考,这里有一些可以使用的其他设置:

对于使用 Azure AD v1 终结点的 .Net,您应该使用 UseWindowsAzureActiveDirectoryBearerAuthentication

这是来自官方 .NET Web API sample 的片段,展示了如何设置它的示例:

public void ConfigureAuth(IAppBuilder app)
{
    app.UseWindowsAzureActiveDirectoryBearerAuthentication(
        new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        {
            Audience = ClientId,
            Tenant = Tenant
        });
}

对于使用 Azure AD v2 端点的 .Net,您应该使用 UseOAuthBearerAuthentication 如下:

public void ConfigureAuth(IAppBuilder app)
{
    TokenValidationParameters tvps = new TokenValidationParameters
    {
        // Accept only those tokens where the audience of the token is equal to the client ID of this app
        ValidAudience = ClientId
    };

    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
    {
        // This SecurityTokenProvider fetches the Azure AD B2C metadata & signing keys from the OpenIDConnect metadata endpoint
        AccessTokenFormat = new JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider(String.Format("https://login.microsoftonline.com/{0}", Tenant)))
    });
}

对于使用 Azure AD v2 端点的 .Net Core,您应该使用 UseJwtBearerAuthentication 如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // ...
    // Other stuff
    // ...

    app.UseJwtBearerAuthentication(
        new JwtBearerOptions
        {
            Authority = string.Format("https://login.microsoftonline.com/{0}/v2.0/", 
                Tenant),
            Audience = ClientId
        });
}