1

I'm adding Microsoft Authentication to Firebase. I'm able to login successfully but I need the user's email and display name. How can I fetch this? So far this is what I have.

export function* signInWithMicrosoft() {
  yield microsoftProvider.setCustomParameters({
    prompt: 'consent',
    tenant: 'consumers',
  });
  const res = yield signInWithPopup(auth, microsoftProvider);

  try {
    const credential = yield OAuthProvider.credentialFromResult(res);
    const { accessToken, idToken } = credential;

    yield console.log(credential);
  } catch (err) {
    return err;
  }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Azrael 998
  • 35
  • 1
  • 6

1 Answers1

2

You can make use of Microsoft Graph API to get signed-in user's email and display name by running below query:

GET https://graph.microsoft.com/v1.0/me

To run the above query, you need to add User.Read permission in your Azure AD application like below:

enter image description here

As you already have access token, just modify your code to run GET request like below:

export function* signInWithMicrosoft() {
  yield microsoftProvider.setCustomParameters({
    prompt: 'consent',
    tenant: 'consumers',
  });
  const res = yield signInWithPopup(auth, microsoftProvider);

  try {
    const credential = yield OAuthProvider.credentialFromResult(res);
    const { accessToken, idToken } = credential;

    const response = yield fetch('https://graph.microsoft.com/v1.0/me', {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    const data = yield response.json();
    const { displayName, mail } = data;

    yield console.log(displayName, mail);
  } catch (err) {
    return err;
  }
}

You can also decode the access token by pasting it in jwt.ms and check scp claim for permissions it has:

enter image description here

When I ran the same GET request in Postman by including Bearer token, I got response successfully with signed-in user's email and display name like below:

GET https://graph.microsoft.com/v1.0/me
Authorization: Bearer <token>

Response:

enter image description here

Sridevi
  • 10,599
  • 1
  • 4
  • 17