使用azure Active Directory作为身份验证提供程序获取用户详细信息

问题描述 投票:1回答:1

我在Azure Web应用程序中托管了一个角度应用程序。我已选择azure活动目录作为身份验证提供程序,如果请求未通过身份验证,则应使用相同的身份登录。因此,基本上,如果用户已经使用他/她的Microsoft帐户登录,则他/她不需要再次登录。

目前,我正在使用.auth / me来获取所有与用户有关的详细信息,例如给定名称,电子邮件等。现在,我需要显示用户的Outlook个人资料图片。为此,我尝试将Graph API与MSAL结合使用,当我使用以下代码时,它可以正常工作:-

async signIn(): Promise<void> {
    let result = await this.msalService.loginPopup(OAuthSettings.scopes)
      .catch((reason) => {
        this.alertsService.add('Login failed', JSON.stringify(reason, null, 2));
      });

    if (result) {
      this.authenticated = true;
      this.user = await this.getUser();
    }
  }

async getAccessToken(): Promise<string> {
    let result = await this.msalService.acquireTokenSilent(OAuthSettings.scopes)
      .catch((reason) => {
        this.alertsService.add('Get token failed', JSON.stringify(reason, null, 2));
      });

    return result;
  }

private async getUser(): Promise<User> {
    if (!this.authenticated) return null;

    let graphClient = Client.init({
      authProvider: async(done) => {
        let token = await this.getAccessToken()
          .catch((reason) => {
            done(reason, null);
          });

        if (token)
        {
          done(null, token);
        } else {
          done("Could not get an access token", null);
        }
      }
    });
    let graphUser = await graphClient.api('/me').get();

    let user = new User();
    user.displayName = graphUser.displayName;
    user.email = graphUser.mail || graphUser.userPrincipalName;

    return user;
  }

由于我不需要任何用户提示,因此我略微更改了signIn()方法,以避免出现如下任何用户提示:-

 async signIn(): Promise<void> {
        let result = this.msalService.loginRedirect(OAuthSettings.scopes);
    this.user = await this.getUser();
    }

更改为此名称后,它将在无限循环中重定向到login.microsoft.com。我找不到任何避免任何形式的提示或重定向的方式来获取所有与用户相关的详细信息,包括个人资料照片。请提出一些实现此目标的方法。我当前用于获取用户名而没有任何用户提示的工作代码如下:-

  getUserName(): Observable<any> {
    return this._http
      .get<any>(this.myAppUrl + '.auth/me', {
        withCredentials: true
      })
      .pipe(catchError(this.errorHandler));
  }
angular azure azure-active-directory msal azure-webapps
1个回答
0
投票

由于您已经在App服务中使用了简单身份验证,因此您可以直接获取访问令牌,而无需再次登录。

您需要配置Web应用程序以请求访问graph api资源。转到Azure资源浏览器->转到站点节点下,然后转到/ config / authsettings

enter image description here

单击编辑按钮,然后将客户端密钥更改为AAD应用程序在高级身份验证设置下配置的密钥。

除了添加客户端密码之外,将其他oginparams更改为以下内容

["response_type=code id_token", "resource=https://microsoft.graph.com"]

enter image description here

然后您的应用程序服务身份验证应开始接收X-MS-TOKEN-AAD-ACCESS-TOKEN标头,您可以使用该标头访问Microsoft Graph API。

参考:

Configuring an App Service to get an Access Token for AAD Graph API

© www.soinside.com 2019 - 2024. All rights reserved.