问题描述
我正在开发一个 Angular 8 应用程序,该应用程序试图检索可供登录用户使用的所有 Microsoft AD 组的列表。 以前,我正在使用 MSAL 库对用户进行身份验证,并成功获得以下值:
- 访问令牌
- idToken
- 家庭标识符
- 过期
我的 MSAL 配置如下:
export function MSALAngularConfigFactory(): MsalAngularConfiguration {
var isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 ||
window.navigator.userAgent.indexOf("Trident/") > -1;
return {
popUp: !isIE,consentScopes: [
'user.read','openid','profile','group.Read.All'
],unprotectedResources: ['https://www.microsoft.com/en-us/'],protectedResourceMap: [
['https://graph.microsoft.com/v1.0/me',['user.read']],['https://graph.microsoft.com/v1.0/groups',['group.read.all']]
]
};
}
export function MSALConfigFactory(): Configuration {
var isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 ||
window.navigator.userAgent.indexOf("Trident/") > -1;
return {
auth: {
clientId: environment.clientId,authority: environment.authority,validateAuthority: true,redirectUri: environment.redirectUrl,postlogoutRedirectUri: environment.redirectUrl,navigatetoLoginRequestUrl: true,},cache: {
cacheLocation: 'localStorage',storeAuthStateInCookie: isIE,}
};
}
当我调用 MSAL 的 getAccount().idTokenClaims['groups'] 方法时,它返回给我的只有一些标识符值的组数组,这不是我的要求。我需要一组 AD 组名称。
我也实现了 MicrosoftGraph 库以使用以下 API 获取群组:
fetch('https://graph.microsoft.com/v1.0/groups',{
headers: {
'Authorization': 'Bearer ' + {access_token},'Content-Type': 'application/json',}
}).then(res => { console.log(res); });
我尝试了 Microsoft Graph 的多种解决方案,包括以下内容:
const msalConfig = {
auth: {
clientId: clientId,// Client Id of the registered application
redirectUri: "https://localhost:4200",}
};
const graphScopes = ["user.read","group.read.all"]; // An array of graph scopes
const msalApplication = new UserAgentApplication(msalConfig);
const options = new MSALAuthenticationProviderOptions(graphScopes);
const authProvider = new ImplicitMSALAuthenticationProvider(msalApplication,options);
this.subscription1 = broadcast.subscribe("msal:loginSuccess",(result) => {
//The result has accesstoken as null.
fetch('https://graph.microsoft.com/v1.0/groups',{
headers: {
'Authorization': 'Bearer ' + {accesstoken},}
}).then(response => { console.log(response);});
CompactToken 解析失败,错误代码:80049217
我尝试了更多解决方案,但没有任何效果。我从昨天开始就陷进去了。
谁能帮我找出最好的解决方案。任何帮助将不胜感激。
提前致谢。
解决方法
不太确定您的应用程序的上下文。我的代码演示基于 this official Angular MSAL demo。
在 src/app/app.module.ts
正确配置此应用后,转到 src/profile/profile.component.ts
添加以下函数以获取所有组名:
getAccessTokenAndCallGraphAPI(){
this.authService.acquireTokenSilent({
scopes: ['group.Read.All']
}).then(result=>{
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',Authorization: 'Bearer '+result.accessToken
})}
this.http.get("https://graph.microsoft.com/v1.0/groups?$select=id,displayName",httpOptions).toPromise().then(result=>{console.log(result)});
})
}
在页面初始化时调用这个函数:
ngOnInit() {
this.getProfile();
this.getAccessTokenAndCallGraphAPI();
}