The blog has moved!
If you are interested in reading new posts, the new URL to bookmark is http://blog.valeriogheri.com/
My current project is an MVC 5 web site that allows users to log in with their Facebook account. The new Asp.Net Identity framework makes it really easy to just drop this feature into your project.
The concept of claims is really interesting but in my opinion it is till a little confused and lacks a clear and “object oriented” way to define the scope of your request and to retrieve lots of most common information withouth having to mess and second guessing some property name, at least for the Facebook provider.
So in my project I have to retrieve the following info for each user:
- email address
- first name
- last name
First of all it’s mandatory to create an application into the Facebook developers portal, configure the scope of your application, that is specifying what permissions your app will need, and obtain an app id and an app secret codes (note that it is mandatory to specify the email in the scope).
Once I had these codes I had to instruct my web app to use them in the OAuth handshake by editing the Startup.Auth.cs file.
I thought this would suffice, having already specified the permissions into the developer’s portal, but in the Account/ExternalLoginCallback action, despite using the right ClaimTypes, Name and Surname, I couldn’t retrieve the right info: Surname was null and Name just gave me the full name. Email worked just fine though.
Finally on StackOverflow I found the right answer in the middle of lots of not working solutions, and I was surprised as it was a little messy just to retrieve something so simple!
Voilà the link to the answer http://stackoverflow.com/questions/20928939/how-to-get-facebook-first-and-last-name-values-using-asp-net-mvc-5-and-owin
Let’s see the code to read those info:
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); var email = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value; var firstName = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:first_name").Value; var lastName = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:last_name").Value;
And that’s it!
Should you need to retrieve more info and you don’t want to play the attribute name guessing game, browse to https://developers.facebook.com/tools/explorer/?method=GET&path=me and play with the tool to find out what you need.
I hope this helps,