1

I am using the Login component <Login /> of the Microsoft Graph Toolkit (React flavor). How can I retrieve the display name and User Principal Name of the logged in user?

I see that the component has a loginCompleted prop, but the user is not passed as argument.

Christophe
  • 27,383
  • 28
  • 97
  • 140
  • 1
    Can you get the `userDetails` object from the login component? in js, something like: let person = document.querySelector('mgt-login') console.log(person.userDetails) This object should contain both the upn and the displayName properties. – Nic Vogt Feb 12 '21 at 21:41
  • 1
    That's the kind of info I am looking for. Obviously I don't want a DOM method such as querySelector and I am looking for a built-in method. There must be one as other components such as Person or Avatar can get the info. – Christophe Feb 12 '21 at 22:11

2 Answers2

1

So it's definitely possible to do this, but be aware that it's not 100% safe (what I mean is, don't rely on this to send to a backend API as a way to authenticate or identify the user). However, for display on the page you can use something like:

import { Providers } from '@microsoft/mgt';
...
let provider = Providers.globalProvider;
let account = provider._userAgentApplication.account;

// now you have access to: account.accountIdentifier, account.name, account.userName, etc.
Hilton Giesenow
  • 9,809
  • 2
  • 10
  • 24
  • Thanks for the reply. What I need is a way to identify the logged in user, that's why I am trying to use the Login feature and move away from a global provider. – Christophe Feb 13 '21 at 16:50
  • You mean like identify for use when calling an API? – Hilton Giesenow Feb 13 '21 at 17:11
  • Yes, I am calling APIs such as me/events or the SharePoint API, and I want to capture the name of the logged in user. The Login component looks safer to me than a provider. – Christophe Feb 13 '21 at 17:30
  • 1
    The Login component is using this same provider under the covers. – Hilton Giesenow Feb 13 '21 at 17:34
  • I understand, but because it does the actual login step I would expect this to be safer than taking the provider value directly. If for some reason the login fails, the user info won't be provided. – Christophe Feb 13 '21 at 17:39
  • 1
    So your best bet in that case is to use MSAL 2.0 directly, I'd think – Hilton Giesenow Feb 13 '21 at 17:41
1

After getting advice from Microsoft, and reviewing a sample, here is the code I came up with:

    <Login
      loginCompleted={(e) => {
        Providers.globalProvider.graph.client.api('me').get()
          .then(gotMe => DoStuff(gotMe));
      }}
      logoutCompleted={(e) => { }}
    />
Christophe
  • 27,383
  • 28
  • 97
  • 140