问题
From angular application i want to call https://login.microsoftonline.com/##tenant##/oauth2/v2.0/token api to get access token from http call and using that token i want to call https://graph.microsoft.com/v1.0/users/##UserId##/getMemberGroups API without using any npm package of angular.
I tried using http service, but getting below error
Access to XMLHttpRequest at 'https://login.microsoftonline.com/xxxx/oauth2/v2.0/token' from origin 'https://xxx.co' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Is there any another way to call Graph API for token and user get login user groups ?
回答1:
It is not allowed to call https://login.microsoftonline.com/<tenant>/oauth2/v2.0/token
directly from a signal page application due to CORS. You should use MSAL for angular to do this. My code is based on this angular official demo.
Pls go to src/app/app.module.ts
to config your Azure Ad:
and run this demo first.
After you run this demo successfully,go to profile.component.ts
, add codes below:
getAccessTokenAndCallGraphAPI(){
this.authService.acquireTokenPopup({
scopes: ['GroupMember.Read.All']
}).then(result=>{
console.log("access token: "+ result.accessToken)
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Bearer '+result.accessToken
})}
const reqBody = {
"securityEnabledOnly": true
}
this.http.post("https://graph.microsoft.com/v1.0/users/<user you want to query>/getMemberGroups",reqBody,httpOptions).toPromise().then(result=>{console.log(result)});
})
}
Call this function when init page:
ngOnInit() {
this.getProfile();
this.getAccessTokenAndCallGraphAPI();
}
result:
Let me know if you have any other questions.
来源:https://stackoverflow.com/questions/65423470/i-want-to-call-token-api-from-microsoft-graph-in-angular-7-http-call