UseJwtBearerAuthentication失败:未经授权的令牌和签名无效 [英] UseJwtBearerAuthentication failed: Unauthorized token and The signature is invalid

查看:1380
本文介绍了UseJwtBearerAuthentication失败:未经授权的令牌和签名无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web api服务和一个Web客户端应用程序来访问Web api.两者都注册在azure活动目录中. 但是,当Web客户端应用程序尝试访问Web api时,我得到了:

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

然后我在 https://jwt.io/上检查了令牌,它确实显示了无效签名" .但是,我不知道这里出了什么问题.

这是我检索令牌的方式:

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;

这是我访问Web 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示例,该示例演示了如何进行设置:

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
        });
}

I am having a web api service and a web client application to access the web api. Both are registered on azure active directory. However, when the web client application tried to access web api, I got :

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

Then I checked the token on https://jwt.io/, it indeed showed "invalid signature". However, I have no idea what is wrong here.

Here is how I retrieved the token:

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;

Here is how I access web api service:

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;

Here is how web api service validates the access:

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

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

Anything wrong here?

Thanks

解决方案

Based on your configuration and code snippets, it look like you're trying to setup a Web API for .Net Core using the Azure AD v1 endpoint.

For .Net Core using the Azure AD v1 endpoint, you should use UseJwtBearerAuthentication as follows:

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
        });
}


For reference, here are some other setups that can be used:

For .Net using the Azure AD v1 endpoint, you should use UseWindowsAzureActiveDirectoryBearerAuthentication

Here's a snippet from the official .NET Web API sample, sample that showcases how to set this up:

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

For .Net using the Azure AD v2 endpoint, you should use UseOAuthBearerAuthentication as follows:

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)))
    });
}

For .Net Core using the Azure AD v2 endpoint, you should use UseJwtBearerAuthentication as follows:

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
        });
}

这篇关于UseJwtBearerAuthentication失败:未经授权的令牌和签名无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆