Tuesday, August 1, 2017

How do I get the user's email when using Microsoft Account Authentication in an MVC project?

Leave a Comment

I have modified startup.Auth.cs so that I could add scopes. Here is what I have:

MicrosoftAccountAuthenticationOptions mo = new MicrosoftAccountAuthenticationOptions() {     ClientId = "My Client ID",     ClientSecret = "My Client Secret", }; app.UseMicrosoftAccountAuthentication(mo); 

This allows me to authenticate the user.

I have tried adding the scopes wl.signin, wl.emails and wl.contacts_emails. However, they cause the Microsoft login page to report the following error: AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope wl.signin, wl.emails, wl.contacts_emails is not valid. The scope combination of openid and email seems to work. However, the scope openid is overkill for what I am trying to do. That is, I think it is too much to ask from the user. The scope email all by it self doesn't work.

This is particularly weird because the template that Visual Studio sets up assumes that the external authentication provider will supply an email address.

How do I get only the user's email?

For context, I am using the following documents: https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference#openid-permissions which gives the impression that I want email and profile included in the scope. However, it goes on to state that they are included by default.

I am trying to implement external Authentication in my MVC project using the document: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins.

3 Answers

Answers 1

You can use the following code to get the email address of a user.

 ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1]; 

Answers 2

Try to add scopes:

MicrosoftAccountAuthenticationOptions mo = new MicrosoftAccountAuthenticationOptions() {     ClientId = "My Client ID",     ClientSecret = "My Client Secret", }; mo.Scope.Add("openid"); mo.Scope.Add("email"); app.UseMicrosoftAccountAuthentication(mo); 

Answers 3

Looks like you have to use OpenID to get the email. However, If you have Microsoft.IdentityModel.Tokens v5.x you can't use OpenID. It only works with Microsoft.IdentityModel.Tokens v4.x. Made the mistake of loading the lates version.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment