登录后如何获取用户名?我正在尝试使用 MSAL (@azure/msal-angular) 进行 Azure 登录

Ras*_*Fay 5 azure-active-directory azure-ad-msal angular

我正在尝试使用 MSAL (@azure/msal-angular) 进行 Azure 登录,并且是 Angular 的新手。我需要在登录后获取用户名并将其显示在 UI 中。提前致谢

unk*_*own 5

您可以用来myMSALObj.getAccount().userName获取用户名。

function showWelcomeMessage() {
    var divWelcome = document.getElementById('WelcomeMessage');
    divWelcome.innerHTML = 'Welcome ' + myMSALObj.getAccount().userName + " to Microsoft Graph API";
    var loginbutton = document.getElementById('SignIn');
    loginbutton.innerHTML = 'Sign Out';
    loginbutton.setAttribute('onclick', 'signOut();');
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅此处

  • 答案已被弃用,有人可以重新打开吗 (4认同)

g00*_*00b 5

您可以从 检索用户MsalService,例如:

const accountInfo: AccountInfo | null = this.msalService.instance.getActiveAccount();
Run Code Online (Sandbox Code Playgroud)

建议等到身份验证过程完成后再调用此方法。这可以通过检查来完成MsalBroadcastService

const account: Observable<AccountInfo | null> = this.msalBroadcastService
    .inProgress$
    .pipe(
        filter(status => status == InteractionStatus.None),
        map(() => {
            const instance: IPublicClientApplication = this.msalService.instance;
            const activeAccount: AccountInfo | null = instance.getActiveAccount();
            const accounts: AccountInfo[] = instance.getAllAccounts();
            if (activeAccount != null) return activeAccount;
            if (accounts.length > 0) {
                const [firstAccount] = accounts;
                instance.setActiveAccount(firstAccount);
                return firstAccount;
            }
            return null;
        })
    );
  
    });
Run Code Online (Sandbox Code Playgroud)