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.
Let’s see the code to read those info:
var externalIdentity = HttpContext.GetOwinContext().
var email = externalIdentity.
FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
var firstName = externalIdentity.
FirstOrDefault(c => c.Type == "urn:facebook:first_name").Value;
var lastName = externalIdentity.
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, follow this link and play with the tool to find out what you need.
I hope this helps,
Italian expat, passionate about modern web development and sci-fi literature