我正在从ADAL迁移到MSAL。
我在角度8中添加了以下配置:
MsalModule.forRoot({
auth: {
clientId: "xxxxx",
authority: "https://login.microsoftonline.com/tenant",
validateAuthority: true,
redirectUri: window.location.href,
postLogoutRedirectUri: "http://localhost:4200/",
navigateToLoginRequestUrl: true
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: isIE, // set to true for IE 11
},
},
{
popUp: false,
consentScopes: ['Directory.AccessAsUser.All',
'user.read',
'openid',
'profile',
'User.ReadWrite',
'User.ReadBasic.All',
'User.Read.All',
'Group.Read.All',
'Directory.AccessAsUser.All'
],
unprotectedResources: ['https://www.microsoft.com/en-us/'],
protectedResourceMap,
extraQueryParameters: {}
}),
此外,我也在尝试通过获取令牌进行验证
const loginRequest = {
scopes: ['user.read','openid', 'profile'],
};
this.authService.acquireTokenSilent(loginRequest);
this.broadcastService.subscribe("msal:acquireTokenFailure", (payload) => {
console.info("acquire token failure " + JSON.stringify(payload));
});
this.broadcastService.subscribe("msal:acquireTokenSuccess", (payload) => {
console.info("acquire token success " + JSON.stringify(payload));
});
在.net端,我编写了以下代码:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
AuthenticationOptions authSettings = Configuration.GetSection("AzureAd").Get<AuthenticationOptions>();
options.Authority = authSettings.Authority;
options.SaveToken = true;
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
// Add the access_token as a claim, as we may actually need it
if (context.SecurityToken is JwtSecurityToken accessToken)
{
if (context.Principal.Identity is ClaimsIdentity identity)
{
identity.AddClaim(new Claim("access_token", accessToken.RawData));
}
}
return Task.CompletedTask;
},
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
((path.StartsWithSegments(SignalRHub) || path.StartsWithSegments(QuillHub))))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
options.TokenValidationParameters = new TokenValidationParameters
{
//Both the client id and app id URI of this API should be valid audiences
ValidAudiences = new List<string> { authSettings.ClientId },
};
});
但是,当我尝试击中令牌时,我会获得令牌成功,但是在api方面,我会收到错误消息,指出发行人'https://login.microsoftonline.com/tenantid/v2.0'无效
我做错了什么?
听起来像后端配置了v1权限,但是您正在获得v2令牌。将您API的配置中的权限更改为:
https://login.microsoftonline.com/tenant/v2.0
啊,实际上那可能还不够。看起来您的前端正在获取Microsoft Graph API的访问令牌。您需要获取API令牌,而不是MS Graph API令牌。为此,请指定在API应用程序注册的“公开API”页面中注册的一个或多个范围。
完成后,您可能会再次使用v1令牌。因此,在更改权限之前,请先执行此操作。