I want to call Token API from Microsoft graph in angular 7+ http call

久未见 提交于 2021-02-11 13:39:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!