首页 文章

Asp.Net - Jwt承载认证:签名无效

提问于
浏览
0

我从我的应用程序AzureAD获取了access_token和id_token,它使用OAuth2和隐式流程 . 这是我获取令牌的示例网址:

https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/authorize?response_type=id_token+token&client_id=my_client_id&state=some_state&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fsign-in&scope=openid%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&nonce=some_nonce

范围是 openid https://grap.microsoft.com/user.read .

response_type是 id_token+token .

我也有一个Asp.Net后端,我想保证 . 所以我使用 Authorize 属性作为我的控制器,并在 Headers 中发送一个令牌,如下所示:"Authentication : Bearer THE_TOKEN" .

我在 Startup.cs 中的配置如下所示:

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    Authority = string.Format("https://login.microsoftonline.com/{0}/v2.0/",
            "d67853c3-db96-4dac-a37b-f2bfb12b42d1"),
    Audience = "8422b3fb-5612-4fdd-a90f-707d7218de57"
});

根据我的阅读,应该使用访问令牌,而id_token不应该离开前端 . 但是后端的身份验证只能在我的情况下使用id令牌 . access_token无法签名 Bearer error="invalid_token", error_description="The signature is invalid" .

看看jwt.io中的access_token,我看到令牌有不同的受众和发行者 . 例如,access_token具有此功能

"aud": "https://graph.microsoft.com",
"iss": "https://sts.windows.net/d67853c3-db96-4dac-a37b-f2bfb12b42d1/",

而id令牌有这个

"aud": "my_client_id",
"iss": "https://login.microsoftonline.com/my_tenant_id/v2.0",

所以在我看来,access_token是以某种方式为Graph API发布的 . 如果有人能告诉我,我做错了什么或我如何能够解决我的问题,我会很高兴的 .

编辑:我在使用范围 openid profile 之前按预期工作 . 但由于Azure的更改,此范围不再有效,Microsoft指示我使用上述范围 .

1 回答

  • 1

    如您所述,您请求的访问令牌是Microsoft Graph . id_token仅供客户端验证用户而不是资源服务器 .

    要使用Azure AD V2.0 endpoints 保护Web API,我们可以获取Web API的访问令牌,如下所示:

    https://login.microsoftonline.com/common/oauth2/v2.0/authorize?response_type=token&client_id={client_id}&scope=api://{client_id}/access_as_user&redirect_uri={redirect_uri}
    

    以下是使用Azure AD V2.0 endpoints 保护Web API的代码:

    public void ConfigureAuth(IAppBuilder app)
    {
        System.Diagnostics.Trace.TraceWarning("Hello");
        var tvps = new TokenValidationParameters
        {
            // The web app and the service are sharing the same clientId
            ValidAudience = clientId,
            ValidateIssuer = false,
        };
    
        // NOTE: The usual WindowsAzureActiveDirectoryBearerAuthenticaitonMiddleware uses a
        // metadata endpoint which is not supported by the v2.0 endpoint.  Instead, this 
        // OpenIdConenctCachingSecurityTokenProvider can be used to fetch & use the OpenIdConnect
        // metadata document.
    
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
            AccessTokenFormat = new JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")),
        });
    }
    

    }

    有关通过Azure AD V2.0 endpoints 保护Web API的更多详细信息,请参阅以下文档:

    Calling a web API from a .NET web app

相关问题