0

我正在尝试将 MSAL 与 angular9 一起使用,这样我就可以访问自定义的“dynamics.com”api 我能够获得登录 API 的有效访问令牌

但由于某种原因,我无法访问此令牌来为自定义 api 发出 GET 请求

这是我的 app.module.ts

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MsalInterceptor, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG } from '@azure/msal-angular';
import { InteractionType,  IPublicClientApplication, PublicClientApplication } from '@azure/msal-browser';

 imports: [
    MsalModule.forRoot( new PublicClientApplication({
      auth: {
        clientId: 'xxxxx-xxxxxxxxxxxx', // This is your client ID
        authority: 'https://xxxx.microsoftonline.com/xxxxxxxxxxxxx', // This is your tenant ID
        redirectUri: 'http://localhost:4200'// This is your redirect URI
              },
      cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: isIE,
      }
      }), {
        interactionType: InteractionType.Popup,
        authRequest: {
          scopes: ['user.read', 'user_impersonation']
        }
      }, {
        interactionType: InteractionType.Popup,
        protectedResourceMap: new Map([ 
          ['https://xxxxxxxxxxx.xxxxxxxxxxxx.dynamics.com/user_impersonation', ['user_impersonation']]
        ])
      })

]

// these are the providers
providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: MsalInterceptor,
          multi: true
        },
        MsalService
        
        
  ],

这是我的 app.component.ts

  apiResponse: string;
constructor(private authService: MsalService, private http: HttpClient,
    ) {}
ngOnInit(): void {
      this.authService.instance.handleRedirectPromise().then( res => {
        if (res != null && res.account != null) {
          this.authService.instance.setActiveAccount(res.account)
        }
      })      

    }
  isLoggedIn(): boolean {
    return this.authService.instance.getActiveAccount() != null
  }

  login() {
    this.authService.loginPopup()
      .subscribe((response: AuthenticationResult) => {
        this.authService.instance.setActiveAccount(response.account);
      });
  }
    callProfile () {
      this.http.get("https://orgb8d5a472.crm17.dynamics.com/api/data/v9.1").subscribe( resp  => {
        this.apiResponse = JSON.stringify(resp)
      })
    }


这是 app.component.html

<button  *ngIf="!isLoggedIn()" (click)="login()">Login</button>
<button  (click)="callProfile()">get</button>

谁能告诉这里有什么问题以及为什么我无法访问生成的令牌并在 API 中使用它?以及为什么每当我按下“获取”按钮时都会得到“获取https://xxxxxxxxx.xxxxxxxx.dynamics.com/api/data/v9.1 401”?

4

1 回答 1

0

可能是一个愚蠢的问题,但你没有说;您的应用程序 ID 是否具有用户模拟 api 权限?

于 2021-10-10T16:22:40.103 回答