简体   繁体   中英

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

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 .

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

您可以使用以下代码获取用户的电子邮件地址。

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

Looks like you have to use ASP.Net Core Web Application (.Net Framework) to get the email. The code is similar but note : MicrosoftAccountOptions instead of MicrosoftAccountAuthenticationOptions .

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

Intrestingly enough this does not notify the user that you are getting their email address. I have Google, Facebook, Twitter, Microsoft & LinkedIn working. Now on to AccountKit for email and SMS logins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM