passport.jsmicrosoft-graph-apiazure-ad-graph-apimicrosoft-account

Get the email address of a Microsoft user


I want to add a login with Microsoft button to my mean-stack application. So I am using passport-microsoft.

By using passport.authenticate('microsoft', { scope: ['User.Read'] }), I could get these information: @odata.context, givenName, surname, displayName id, userPrincipalName, businessPhones, jobTitle, mail, mobilePhone, officeLocation, preferredLanguage. For me, my userPrincipalName is an email address, whereas my mail is null.

I have setup the application as follows, but if I write passport.authenticate('microsoft', { scope: ['User.Read', 'email'] }), the authentication gave me an "invalid scope" error.

enter image description here

Does anyone know how to setup my application and request to get the email address of a user?


Solution

  • If you look at the documentation for the user object, you will find the following:

    mail

    String

    The SMTP address for the user, for example, "jeff@contoso.onmicrosoft.com". Read-Only. Supports $filter.

    userPrincipalName

    String

    The user principal name (UPN) of the user. The UPN is an Internet-style login name for the user based on the Internet standard RFC 822. By convention, this should map to the user's email name. The general format is alias@domain, where domain must be present in the tenant’s collection of verified domains. This property is required when a user is created. The verified domains for the tenant can be accessed from the verifiedDomains property of organization. Supports $filter and $orderby.

    So it seems the mail property does not necessarily represent the email address for the user, but is used specifically with Outlook and Office 365. It is also not a required property when creating a user. Instead, you should rely on the userPrincipalName to be the email for the user.

    As for your error with the scope, you should share the full error message.