I am developing a web site in ASP.NET MVC 5 (using RC1 version currently). The site will use Facebook for user authentication and for retrieving initial profile data.
For the authentication system I am using the new OWIN based ASP.NET Identity engine (http://blogs.msdn.com/b/webdev/archive/2013/07/03/understanding-owin-forms-authentication-in-mvc-5.aspx), since it greatly simplifies the process of authenticating with external providers.
The problem is that once a user first logs in, I want to get its email address from the Facebook profile, but this data is not included in the generated claims. So I have thought on these alternatives to get the address:
Instruct the ASP.NET Identity engine to include the email address in the set of data that is retrieved from Facebook and then converted to claims. I don't know if this is possible at all.
Use the Facebook graph API (https://developers.facebook.com/docs/getting-started/graphapi) to retrieve the email address by using the Facebook user id (which is included in the claims data). But this will not work if the user has set his email address as private.
Use the Facebook graph API, but specifying "me" instead of the Facebook user id (https://developers.facebook.com/docs/reference/api/user). But an access token is required, and I don't know how to (or if it's possible at all) retrieve the access token that ASP.NET uses to obtain the user data.
So the question is:
How can I instruct the ASP.NET Identity engine to retrieve additional information from Facebook and include it in the claims data?
Or alternatively, how can I retrieve the generated access token so that I can ask Facebook myself?
Thank you!
Note: for the authentication system my application uses code based on the sample project linked in this SO answer: https://stackoverflow.com/a/18423474/4574
OWIN includes middleware components for authentication, including support for log-ins using external identity providers (like Microsoft Accounts, Facebook, Google, Twitter), and log-ins using organizational accounts from on-premises Active Directory or Azure Active Directory.
ASP.NET Core Identity is a membership system which allows you to add login functionality to your application. Users can create an account and login with a user name and password or they can use an external login providers such as Facebook, Google, Microsoft Account, Twitter and more.
Create a new Microsoft.Owin.Security.Facebook.AuthenticationOptions object in Startup.ConfigureAuth (StartupAuth.cs), passing it the FacebookAppId, FacebookAppSecret, and a new AuthenticationProvider. You will use a lambda expression to pass the OnAuthenticated method some code to add Claims to the identity which contain the values you extract from context.Identity. This will include access_token by default. You must add email to the Scope. Other user properties are available from context.User (see link at bottom for example).
StartUp.Auth.cs
// Facebook : Create New App // https://dev.twitter.com/apps if (ConfigurationManager.AppSettings.Get("FacebookAppId").Length > 0) { var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions() { AppId = ConfigurationManager.AppSettings.Get("FacebookAppId"), AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"), Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider() { OnAuthenticated = (context) => { context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook")); context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:email", context.Email, XmlSchemaString, "Facebook")); return Task.FromResult(0); } } }; facebookOptions.Scope.Add("email"); app.UseFacebookAuthentication(facebookOptions); }
In AccountController, I extract the ClaimsIdentity from the AuthenticationManager using the external cookie. I then add it to the identity created using the application cookie. I ignored any claims that starts with "...schemas.xmlsoap.org/ws/2005/05/identity/claims" since it seemed to break the login.
AccountController.cs
private async Task SignInAsync(CustomUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); // Extracted the part that has been changed in SignInAsync for clarity. await SetExternalProperties(identity); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); } private async Task SetExternalProperties(ClaimsIdentity identity) { // get external claims captured in Startup.ConfigureAuth ClaimsIdentity ext = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); if (ext != null) { var ignoreClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims"; // add external claims to identity foreach (var c in ext.Claims) { if (!c.Type.StartsWith(ignoreClaim)) if (!identity.HasClaim(c.Type, c.Value)) identity.AddClaim(c); } } }
And finally, I want to display whatever values are not from the LOCAL AUTHORITY. I created a partial view _ExternalUserPropertiesListPartial that appears on the /Account/Manage page. I get the claims I previously stored from AuthenticationManager.User.Claims and then pass it to the view.
AccountController.cs
[ChildActionOnly] public ActionResult ExternalUserPropertiesList() { var extList = GetExternalProperties(); return (ActionResult)PartialView("_ExternalUserPropertiesListPartial", extList); } private List<ExtPropertyViewModel> GetExternalProperties() { var claimlist = from claims in AuthenticationManager.User.Claims where claims.Issuer != "LOCAL AUTHORITY" select new ExtPropertyViewModel { Issuer = claims.Issuer, Type = claims.Type, Value = claims.Value }; return claimlist.ToList<ExtPropertyViewModel>(); }
And just to be thorough, the view:
_ExternalUserPropertiesListPartial.cshtml
@model IEnumerable<MySample.Models.ExtPropertyViewModel> @if (Model != null) { <legend>External User Properties</legend> <table class="table"> <tbody> @foreach (var claim in Model) { <tr> <td>@claim.Issuer</td> <td>@claim.Type</td> <td>@claim.Value</td> </tr> } </tbody> </table> }
The working example and complete code is on GitHub: https://github.com/johndpalm/IdentityUserPropertiesSample
And any feedback, corrections, or improvements would be appreciated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With