azure 我使用MSAL在我的Angular应用程序中使用Microsoft帐户进行身份验证,我可以访问用户名,我很难找到

t1rydlwq  于 2023-10-22  发布在  Angular
关注(0)|答案(1)|浏览(149)

在Appmodule中
{
interactionType:InteractionType.Redirect,
protectedResourceMap:新Map([
[
'https://graph.microsoft.com/v1.0/me',
请输入'user. Read','email','profile'],
],
“/API/”,“API://7bb5-8f/API.scope']],
]),
}
在组分
public void run(){
if(){
this.router.navigate([this.router.url]);
this.callProfile();
}否则{
if(this.msalGuardConfig.authRequest){
this.msalService.loginRedirect({
. this.msalGuardConfig.authRequest,
} as RedirectRequest);
}否则{
getName();
}
}
}
public void run(){
httpClient.get(“https://graph.microsoft.com/v1.0/me“).subscribe(
(resp:GraphApiResponse)=> {
console.log('用户ID:',resp.id);
this.generateImageSource(resp);
},
(error)=> {
console.error('获取配置文件时出错:',error);
}
);
}
但我是取用户id但在图像给404
generateImageSource ID:e//a2
graph.microsoft.com/v1.0/users/**e//
****/a2/photo/$value:1
无法加载资源:服务器响应状态为401(未授权)
请帮助我获取用户配置文件有没有从Azure访问的问题。

fae0ux8s

fae0ux8s1#

这里是我能够获取用户名和图像的方式

1:安装了Angular的MSAL

npm install --save @azure/msal-angular 
npm install --save @azure/msal-browser

2:创建了显示用户信息的组件

import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
import { MsalService } from '@azure/msal-angular';

@Component({
  selector: 'app-profile',
  template: `
    <h1>User Profile</h1>
    <div *ngIf="isAuthenticated">
      <h2>Welcome, {{ userDisplayName }}</h2>
      <img [src]="userImageUrl" alt="User Image" />
    </div>
  `,
})
export class ProfileComponent {
  isAuthenticated: boolean = false;
  userDisplayName: string | undefined;
  userImageUrl: string | undefined;

  constructor(private authService: AuthService, private msalService: MsalService) {
    this.isAuthenticated = this.msalService.instance.getAllAccounts().length > 0;
    if (this.isAuthenticated) {
      const user = this.msalService.instance.getAllAccounts()[0];
      this.userDisplayName = user.name || 'User';
      this.userImageUrl = user.idTokenClaims ? user.idTokenClaims['upn'] : 'default-image-url';
    }
  }
}

3.配置MSAL模块:在您的app.module.ts中,确保已设置访问Microsoft Graph API所需的作用域。这将包括User.Read示波器。

const  GRAPH_ENDPOINT  =  'https://graph.microsoft.com/v1.0/me';
export  function  MSALInterceptorConfigFactory():  MsalInterceptorConfiguration {

const  protectedResourceMap  =  new  Map<string, Array<string>>();
protectedResourceMap.set(GRAPH_ENDPOINT, ['user.read']);
return {
interactionType:  InteractionType.Redirect,
protectedResourceMap,
};
}

结果

相关问题