我从 AzureAD 为我的应用程序获取了 access_token 和 id_token,该应用程序使用 OAuth2 和隐式流程。这是我获取令牌的示例 URL:
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
属性,并在标头中发送令牌,如下所示: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 Graph。并且id_token仅用于客户端验证用户身份,不用于资源服务器。
要使用 Azure AD V2.0 端点保护 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 端点保护 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 端点保护 Web API 的更多详细信息,您可以参考以下文档: