Retrieving Email From Google, Microsoft And Facebook External Login Provider

Retrieving 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 in general, for that there are some good resources already, one of them is OAuth for Asp.Net, 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 twitter team.

Retrieving email form Google external login provider

With google external login provider, you don’t have to do anything especial to retrieve the email, if you set up your GoogleOAuth2AuthenticationOptions in Startup.Auth.cs correctly, you can retrieve the email form 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:

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

Retrieving email form Microsoft external login provider

First thing you need to do is to set up your MicrosoftAccountAuthenticationOptions and creating the ClientId and ClientSectret, but if you want to ask for user’s email and other info, you should also add something called Scope, by adding scope you asking the API for user’s permission to disclose this information:

  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:

  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:

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

And in your ExternalLoginConfirmation method:

      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 informations that we want, this method can be used to retreve 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 check 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.

Share...
 

Hamid Mosalla

Hi, I'm Hamid Mosalla, I'm a software developer, indie cinema fan and a classical music aficionado. Here I write about my experiences mostly related to web development and .Net.