Oauth 2.0 UseJwtBeareAuthentication失败:未经授权的令牌和签名无效

Oauth 2.0 UseJwtBeareAuthentication失败:未经授权的令牌和签名无效,oauth-2.0,jwt,azure-active-directory,bearer-token,Oauth 2.0,Jwt,Azure Active Directory,Bearer Token,我有一个web api服务和一个web客户端应用程序来访问web api。两者都在azure active directory上注册。 但是,当web客户端应用程序尝试访问web api时,我得到: ReasonPhrase: 'Unauthorized' WWW-Authenticate: Bearer error=\"invalid_token\", error_description=\"The signature is invalid 然后我检查了一下令牌,它确实显示了“无效签名”。然

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

ReasonPhrase: 'Unauthorized'
WWW-Authenticate: Bearer error=\"invalid_token\", error_description=\"The signature is invalid
然后我检查了一下令牌,它确实显示了“无效签名”。然而,我不知道这里出了什么问题

下面是我如何检索令牌的:

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服务如何验证访问:

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,您应该使用
UseJWTBeareAuthentication
如下所示:

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

以下是一些可以使用的其他设置,以供参考:

对于使用Azure AD v1端点的.Net,您应该使用
useWindowsAzureActiveDirectoryBeareAuthentication

以下是官方示例中的一个片段,展示了如何设置:

public void ConfigureAuth(IAppBuilder app)
{
    app.UseWindowsAzureActiveDirectoryBearerAuthentication(
        new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        {
            Audience = ClientId,
            Tenant = Tenant
        });
}
对于使用Azure AD v2端点的.Net,您应该使用
UseAuthBeareAuthentication
,如下所示:

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
        });
}
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)))
    });
}
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
        });
}
对于使用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}/", 
                Tenant),
            Audience = ClientId
        });
}
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)))
    });
}
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
        });
}

不完全确定这是否有帮助,因此我将添加以下内容作为评论。我看不出您在web api中设置了受众或权限,请参见此处的示例。此外,jwt.io将不会验证令牌签名,除非您遵循以下步骤。net core不支持直接使用WindowsAzureActiveDirectoryBeareAuthentication。感谢Saca花时间回答我的问题。但是.net内核没有“ConfigureAuth”功能。相反,.net core只有“Configure”,其参数是“IAppBuilder”而不是“IAppBuilder”。因此,更新后的答案仍然无法在.core net.ConfigureAuth中工作。它只是为所有auth内容创建帮助器方法的模式的一部分。您可以在Configure方法中执行相同的操作。IApplicationBuilder没有“UseJwtBearer”方法。对不起,输入错误,是“UseJwtBeareAuthentication”,我更新了答案。道歉。