Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Retrieving Email From Google, Microsoft And Facebook External Login Provider

4.93/5 (6 votes)
30 Dec 2015CPOL2 min read 21K  
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)