【问题标题】:UseJwtBearerAuthentication failed: Unauthorized token and The signature is invalidUseJwtBearerAuthentication failed: Unauthorized token and The signature is invalid
【发布时间】:2017-10-27 22:06:57
【问题描述】:

我有一个 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",
      }
  });

这里有什么问题吗?

谢谢

【问题讨论】:

标签: oauth-2.0 jwt azure-active-directory bearer-token


【解决方案1】:

根据您的配置和代码 sn-ps,您似乎正在尝试使用 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 的 sn-p,展示了如何设置的示例:

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

【讨论】:

  • .net core 不直接支持 UseWindowsAzureActiveDirectoryBearerAuthentication。
  • 感谢 Saca 抽出时间回答我的问题。但是.net core 没有“ConfigureAuth”功能。相反,.net 核心只有“配置”,其参数是“IApplicationBuilder”而不是“IAppBuilder”。因此,您更新的答案仍然无法在 .core 网络中使用。
  • ConfigureAuth 只是为所有身份验证内容创建辅助方法的模式的一部分。您可以在 Configure 方法中执行相同的操作。
  • IApplicationBuilder 没有方法“UseJwtBearer”。
  • 对不起,错字,它是“UseJwtBearerAuthentication”,我更新了答案。道歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-18
  • 2022-11-20
  • 2022-12-01
  • 2022-11-17
  • 2021-09-27
  • 2022-11-10
  • 2022-11-20
相关资源
最近更新 更多