无法使用 Msal Angular 9 获取自定义 API



我正在尝试使用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中使用它?为什么我得到'GET https://xxxxxxxxx.xxxxxxxx.dynamics.com/api/data/v9.1 401'每当我按下"Get"按钮?

可能是一个愚蠢的问题,但你没有说;你的app Id有用户模拟api权限吗?

我设法通过删除'user来获得我的工作。读取'作用域并将'user_impersonation'更改为'https://xxxxxxxxxxx.xxxxxxxxxxxx.dynamics.com/user_impersonation'。在地图项上,我删除了URL上的'user_impersonation'部分,使其变成以下内容:['https://xxxxxxxxxxx.xxxxxxxxxxxx.dynamics.com', ['user_impersonation']]

我也将API URL更改为9.2版本,但它在9.1和9.2上都可以工作。

最新更新