Get User's Email Address from Facebook with ASP.NET Web Forms

Join my mailing list! Download the sample project on GitHub | Follow me on Twitter at @nickpinheir

In my previous post, ‘Facebook Login with ASP.net Web Forms’, I covered social login, OAuth and accessing a user’s public profile information.  Incorporating these core functions into your web app opens the door to a world of possibilities.  You now have the necessary foundation required to truly leverage the many capabilities of the Facebook platform.  In this post I will detail how to request and obtain the most valuable piece of user information, the email address.

Permission

In order to access a Facebook user’s email address, you must receive permission from the user.  This permission can be obtained either during the Facebook Login process or at the point at which you need the email address in your web app.  If you downloaded the sample Visual Studio project from my previous post and dug in a little, you may have noticed the URL the ‘Login with Facebook’ link pointed to.  The link is as follows:

https://www.facebook.com/v2.0/dialog/oauth/?client\_id=\[Your Facebook App Id]&redirect_uri=[Your Redirect URI]&response_type=code&state=1

In order for us to request permission to the user’s email address all we need to do is add one query string parameter to this link.  The parameter is ‘scope’ and the value will be ‘email’.  I have highlighted the addition in green below:

https://www.facebook.com/v2.0/dialog/oauth/?client\_id=\[Your Facebook App Id]&redirect_uri=[Your Redirect URI]&response_type=code&state=1&scope=email

The scope parameter is used to request permission to all non-publicly available properties and actions of the Facebook user.  We’ll see in upcoming posts how to also request permission to post a status update to the user’s timeline using the ‘publish_actions’ scope.

Believe it or not adding the scope parameter and value is the only addition required to request the user’s email address.  Once we have added scope to the Facebook Login URL we will notice the addition of ‘email address’ in the login dialogue.  As seen in the screenshot below the login dialogue now states “msdevz will receive the following info: your public profile and email address.”

Access Token

Provided the user approves your request for their email address the resulting access token we request will include this permission. As a reminder, the OAuth dialogue will provide us a response including a ‘code’ parameter. We use the value of the code parameter to request an access token via the following endpoint:

https://graph.facebook.com/oauth/access\_token?client\_id=\[Your Facebook App Id]&client_secret=[Your Facebook App Secret]&redirect_uri=[Your Redirect URI]&code=[Code Received from Response]

Graph API

Now that the user has authorized access to their email address, next we need to make a request to the following Facebook Graph API endpoint which returns the user’s profile information:

https://graph.facebook.com/me?access\_token=\[User’s Access Token]

The JSON object response we receive will now include the email address. Here’s a screenshot of the response using Fiddler:

And here is the resulting page in the sample Visual Studio project:

And there you have it.  Please let me know in the comments if you have any issue with the concept or with the sample project… would be happy to help.

Steps in Review:

  1. User logs into your app using Facebook Login
  2. User accepts permission request to public profile information and email address
  3. Exchange code for access token
  4. Request user’s profile properties now including email address via Graph API

Download the sample project on GitHub:
https://github.com/nickpinheiro/FacebookLoginASPnetWebForms/tree/email

In my next blog post here in the Facebook Developer series I will discuss how to:

  • Publish to Facebook with ASP.net Web Forms

 

  Nick Pinheiro is an experienced software engineer, technologist, speaker, author and evangelist. He is a Senior Consultant in the Azure Applications Circle of Excellence (CoE) at Microsoft where he develops cloud-based, web and mobile applications for the world’s largest organizations. He speaks at various industry conferences on Modern Apps, Social and Cloud. Follow him on Twitter at @nickpinheir.

 

Join my mailing list!

Comments

  • Anonymous
    July 09, 2015
    Hey am using the same downloaded file but still not getting email infos.

  • Anonymous
    July 09, 2015
    @Jack - Ok.  Please elaborate a bit on what you are in fact getting.  Are you receiving other public profile information?  Are you receiving an error?  Have you added your App Id and App Secret to the web.config file?

  • Anonymous
    October 02, 2015
    sir when i code for getting email from facebook i get error Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.

  • Anonymous
    October 05, 2015
    @Shams - Ok, all you need to do is navigate to 'developers.facebok.com'.  Log in if you are not already logged in.  Click on 'My Apps' in the top navigation and select your Facebook app.  Click on 'Settings' on the left navigation.  Click on '+ Add Platform' and select Website.  In Site URL enter 'http://localhost'.  And then on the form above under 'App Domains' enter 'localhost'.  Click Save Changes and try running the solution again in Visual Studio.

  • Anonymous
    October 28, 2015
    Hi Nick, thank you for the great post. I have 2 questions; Is it possible to have the login happen in a popup instead of a full page that navigates away from my site? Also how do we handle when the user fails to authenticate with Facebook?

  • Anonymous
    October 28, 2015
    Hi Nick, sorry I forgot to ask how I can get the Date of Birth as well?

  • Anonymous
    October 28, 2015
    @Takwirira - Yes, you can have the login happen in a popup by using the JavaScript SDK and the 'Login Button' provided by Facebook:  developers.facebook.com/.../login-button If a user fails to authenticate with Facebook they won't be able to make it back to your app and therefore there's essentially nothing for you to handle. You can get the Date of Birth by using the 'user_birthday' scope in your login request just as we did with 'email' above. Let me know if you have any additional questions :)

  • Anonymous
    October 28, 2015
    @All - I just published a new post: 'Publish to Facebook with ASP.net Web Forms' blogs.msdn.com/.../publish-to-facebook-with-asp-net-web-forms.aspx

  • Anonymous
    October 28, 2015
    Awesome! Thank you Nick - how do I add the 'user_birthday' together with 'email' i.e. after "&scope=email" I have tried "&scope=email,user_birthday" with no luck

  • Anonymous
    October 28, 2015
    I also tried to get the "age_range" since its part of the public profile I get error "'FacebookLoginASPnetWebForms.Models.Facebook+User' does not contain a property with the name 'age_range'."

  • Anonymous
    October 28, 2015
    I've just noticed that age_range is there but being returned as   "age_range": {"min": 21}," so probably causing the error. Birthday would be much better and straight to the point perhaps.

  • Anonymous
    October 29, 2015
    Hey Nick, I've been playing around with the code again and wondered ... if I am at Default.aspx with a query string e.g. Default.aspx?custom=1234 then I click the hyperlink to go to Facebook and back to Account/User.aspx is there any chance of still retrieving the value for custom i.e. can I pass it in the initial request and get it back? At the moment I am not getting it back so my workaround is a session variable.

  • Anonymous
    October 30, 2015
    @Takwirira - No, you wouldn't get the query string parameter and value back unless you added it to the 'redirect_uri' which is stored as part of the dialog url in 'Default.aspx.cs'.

  • Anonymous
    October 30, 2015
    @Takwirira - Yes, you would add the 'user_birthday' scope in the following convention along with 'email':  'scope=email,user_birthday'.  That will provide you with the permission to add the 'birthday' field to the /me endpoint which would then look like this to get the birthday: graph. facebook. com/me?fields=first_name,last_name,gender,link,locale,email,birthday&access_token=" + accessToken

  • Anonymous
    November 03, 2015
    Thanks Nick, I can get the birthday fine now. I sent the parameter (test=123) in the request_uri  + "&redirect_uri=http://" + Request.ServerVariables("SERVER_NAME") + ":" + Request.ServerVariables("SERVER_PORT") + "/fbResponse.aspx&test=1234&response_type=code&state=1&scope=email,user_birthday" But I don't know how to collect it when it returns because the returning URL simply has the code string

  • Anonymous
    November 06, 2015
    hi, i want to get user's birthday. can you please tell how do i get?

  • Anonymous
    November 08, 2015
    Hi Mohit, First URL (Request Page) "www.facebook.com/.../oauth + ConfigurationManager.AppSettings("FacebookAppId") + "&redirect_uri=http://" + Request.ServerVariables("SERVER_NAME") + ":" + Request.ServerVariables("SERVER_PORT") + "/YourResponsePage.aspx&response_type=code&state=1&scope=email,user_birthday" Second URL (YourResponsePage) graph.facebook.com/me) & accessToken

  • Anonymous
    November 29, 2015
    Hi, It works fine on my local system, but when i hosted in the server it showing 404 error bad request can please suggest me how to do

  • Anonymous
    January 05, 2016
    How can I get image url of the user who is logging in??

  • Anonymous
    January 13, 2016
    @Stan - The user profile image of your current user can easily be called by using the Facebook Id of the user in the following URL: http://graph.facebook.com/[id]/picture?type=large.  For example the following is my user profile image URL:  graph.facebook.com/.../picture.   Note that you receive the Facebook Id of the user in the JSON response of the Facebook Graph API endpoint which returns the user’s profile information:  graph.facebook.com/me

  • Anonymous
    February 12, 2016
    SIR I WANT TO SEE MY FRIEND EMAIL ADDRESS B.COZ HIS ACCOUNT WAS HACKED BY SOME ONE

  • Anonymous
    March 07, 2016
    Hello All! Join my just released mailing list for free content, videos, blog posts, webinars, eBooks and more! http://www.nick-pinheiro.com

  • Anonymous
    November 10, 2017
    This design is spectacular! You obviously know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost...HaHa!) Great job.I really enjoyed what you had to say, and more than that,how you presented it. Too cool!

  • Anonymous
    March 09, 2018
    Please share the post which will fetch email id of all my friends.

    • Anonymous
      March 09, 2018
      Hi Sathiyamoorthy. Unfortunately the Facebook Graph API doesn't allow this type of request. The best way to go about this would be to create a Facebook App and to ask all your friends to log into it and allow their email addresses. You could use the 'Facebook Solution Framework (FSF) NuGet Package' I have developed to accomplish this. The documentation can be found here: https://www.modernappz.com/products/fsf/nuget/docs/getting-started.