Click here to Skip to main content
15,879,535 members
Articles / All Topics

Retrieving Email From Google, Microsoft And Facebook External Login Provider

Rate me:
Please Sign up or sign in to vote.
4.93/5 (6 votes)
30 Dec 2015CPOL2 min read 20.4K   7   7
How to retrieve email from Google, Microsoft And Facebook External Login Provider

Introduction

In this post, I’m going to show you how you can retrieve email address form the OAuth external login providers of Facebook, Google, and Microsoft in ASP.NET MVC applications, I'm not going to discuss how you can use these providers, for that, there are many good resources you can look into. One of them is OAuth for ASP.NET (Update: site is now down but source code available at github), I also discuss twitter and that it doesn’t allow you to retrieve email, at least not without requesting this feature to be enabled after you send a request to the twitter team.

Retrieving Email form Google External Login Provider

With Google external login provider, you don’t have to do anything special to retrieve the email, if you set up your GoogleOAuth2AuthenticationOptions in Startup.Auth.cs correctly, you can retrieve the email from the Email property of the ExternalLoginInfo class and use it when registering the user, of course, if you don’t use the email for user’s login:

C#
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
string email = info.Email;

Retrieving Email form Microsoft External Login Provider

The first thing you need to do is to set up your MicrosoftAccountAuthenticationOptions and create the ClientId and ClientSecret, but if you want to ask for user’s email and other information, you should also add something called Scope, by adding Scope you are asking the API for user’s permission to disclose this information:

C#
var microsoftOptions = new MicrosoftAccountAuthenticationOptions
 {
   Caption = "Example Microsoft Account Authentication",
   ClientId = "000000054f5f5",
   ClientSecret = "Yx6IAzobgdfgdfguHSgN5857oUT4zzk",
   Scope = { "wl.emails", "wl.basic" }
 };
app.UseMicrosoftAccountAuthentication(microsoftOptions);

Next, in your ExternalLoginConfirmation method, you can use this to retrieve the email of the user when user tries to login using Microsoft account:

C#
var info = await AuthenticationManager.GetExternalLoginInfoAsync();

if (info.Login.LoginProvider == "Microsoft")
  {
   var identity = await AuthenticationManager.AuthenticateAsync(
                       DefaultAuthenticationTypes.ExternalCookie);

   var emailClaim = identity.Identity.FindFirst(ClaimTypes.Email);
                  info.Email = emailClaim.Value;
  }

Retrieving Email form Facebook External Login Provider

To retrieve the email using Facebook external login provider, you have to use a package. This package gives you the FacebookClient class that you can use to query Facebook for user information, for example, for retrieving email form Facebook, you first need to add the AppId and AppSecret and then specify what you want to get form the Facebook API by adding that as a scope and finally save the AccessToken as a claim:

C#
var faceBookOptions = new FacebookAuthenticationOptions
   {
     AppId = "169866578967501",
     AppSecret = "b6wer3dwer5ertg8er8cbrtyefe",
     Scope = { "email" },
     Provider = new FacebookAuthenticationProvider
      {
        OnAuthenticated = context =>
          {
            context.Identity.AddClaim(new System.Security.Claims.Claim
                                     ("FacebookAccessToken", context.AccessToken));
            return Task.FromResult(true);
           }
         }
      };
      app.UseFacebookAuthentication(faceBookOptions);

And in your ExternalLoginConfirmation method:

C#
if (info.Login.LoginProvider == "Facebook")
    {
      var identity = AuthenticationManager.GetExternalIdentity
                                  (DefaultAuthenticationTypes.ExternalCookie);
      var accessToken = identity.FindFirstValue("FacebookAccessToken");
      var fb = new FacebookClient(accessToken);
      dynamic myInfo = fb.Get("/me?fields=email");
      info.Email = myInfo.email;
    }

Here, we first retrieve the authentication token, then we use that token to get an instance to the FacebookClient, and then we query the instance for the information that we want. This method can be used to retrieve any other kind of information not just email, we just need to add the necessary scope and use the FacebookClient instance the same way, of course we need to make sure that we have the necessary permission in the Facebook developer center.

Retrieving Email form Twitter External Login Provider

The twitter by default doesn’t provide the user’s email, we need to ask the twitter to enable it for us using this form, twitter then checks your app and if you pass a certain criteria, they’re going to enable it and you can use it in your app, or you can always ask the user to provide the email if the provider was twitter.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
Programming is my passion, because I find it so intellectually rewarding. I currently work as a back-end web developer, using Microsoft technology stack, I also blog about my experiences and contribute to open source projects on my free time.

Comments and Discussions

 
QuestionGetExternalLoginInfoAsync does not belong to AuthenticationManager Pin
Jaime Stuardo - Chile27-Nov-20 11:48
Jaime Stuardo - Chile27-Nov-20 11:48 
Hello,

I am using a custom user store, so I am having troubles actually logging the user in after he come back from the external provider.

In that case, the method FindAsync(UserLoginInfo login) is called but, how can I actually log the user in?

login parameter only contains a key and the name, that in this case is Google.

One attempt was this:

C#
public Task<T> FindAsync(UserLoginInfo login)
{
    var info = AuthenticationManager.GetExternalLoginInfoAsync().Result;
    var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
}


but the error is shown.

Any idea of how to do this?

thanks
Jaime
QuestionGood Information Pin
DFX1014-Jan-16 5:41
DFX1014-Jan-16 5:41 
SuggestionClient secret key. Pin
kaviteshsingh31-Dec-15 18:54
kaviteshsingh31-Dec-15 18:54 
GeneralRe: Client secret key. Pin
Hamid Mosalla1-Jan-16 4:59
Hamid Mosalla1-Jan-16 4:59 
PraiseThank You Hamid Pin
Member 1223736030-Dec-15 19:58
Member 1223736030-Dec-15 19:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.