Search code examples
javascriptoauth-2.0firebase-authenticationazure-active-directorymicrosoft-oauth

Microsoft OAuth - After sign in how do I get the user's email and display name?


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;
  }
}

Solution

  • 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