【发布时间】:2020-08-18 20:30:08
【问题描述】:
目标:使用 Microsoft 登录对话框在前端登录 Azure AD 用户。将令牌附加到后端请求。在后端验证令牌以确保只有授权用户才能访问代码。棘手的部分:手动验证,因为它不是唯一的身份验证。
我已成功登录并发送令牌,但在验证时出现如下错误:IDX10511: Signature validation failed. Keys tried: ...
这是我目前所拥有的:
app.module.ts
@NgModule({
declarations: [
AppComponent,
RestrictedPageComponent
],
imports: [
HttpClientModule,
MsalModule.forRoot({
auth: {
clientId: '<CLIENT ID>',
}
}, {
consentScopes: [
'user.read',
'openid',
'profile',
],
protectedResourceMap: [
['https://localhost:44323/v1/login', ['user.read']], // frontend
['https://localhost:5001/api/Login', ['user.read']] // backend
]
}),
BrowserModule,
AppRoutingModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
],
bootstrap: [AppComponent]
})
export class AppModule { }
login.component.ts
login() {
const loginRequest = { scopes: ['https://graph.microsoft.com/User.ReadWrite'] };
this.authService.loginPopup(loginRequest);
}
这似乎工作得很好。我可以通过 Microsoft 登录,然后 MsalInterceptor 将不记名令牌添加到后端请求标头。
在后端,我现在只想验证令牌是否有效以及用户是否通过了正确的身份验证。
private JwtSecurityToken Validate(string token)
{
var stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
// also tried "https://login.microsoftonline.com/<TENANT ID>/v2.0/.well-known/openid-configuration"
var openIdConnectConfigurationRetriever = new OpenIdConnectConfigurationRetriever();
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, openIdConnectConfigurationRetriever);
var config = configManager.GetConfigurationAsync().Result;
var validationParameters = new TokenValidationParameters
{
IssuerSigningKeys = config.SigningKeys,
// just for now
ValidateAudience = false,
ValidateIssuer = false,
ValidateLifetime = false
};
var tokenHandler = new JwtSecurityTokenHandler();
IdentityModelEventSource.ShowPII = true;
token = token.Replace("Bearer ", string.Empty); // weird - the token starts with "Bearer " and is not valid like this
var result = tokenHandler.ValidateToken(token, validationParameters, out var jwt);
return jwt as JwtSecurityToken;
}
在调用tokenHandler.ValidateToken(... 时,我总是收到类似IDX10511: Signature validation failed. Keys tried: ... 的错误。
我不确定我是否正确理解并使用了整个概念。
我对 Azure Bearer 令牌的使用和验证的了解越多,我就越感到困惑。
我可以解析http://jwt.io 上的令牌,但签名始终无效。
后端能否在不传递任何共享密钥或客户端 ID 的情况下验证令牌? 这是开始的正确方法吗?
编辑:我不确定我是否使用了正确的端点来调用前端和后端以及不同端点扮演的角色(例如:有或没有租户 ID)。如果有人能解释一下就好了。
BR马蒂亚斯
【问题讨论】:
-
请参阅下面的答案。仅此外:对于手动令牌验证,我必须将
stsDiscoveryEndpoint更改为https://login.microsoftonline.com/<TENANT ID>/v2.0/.well-known/openid-configuration
标签: asp.net-core azure-active-directory microsoft-graph-api bearer-token