Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identity Server 3 Facebook Login Get Email

Identity server is implemented and working well. Google login is working and is returning several claims including email.

Facebook login is working, and my app is live and requests email permissions when a new user logs in.

The problem is that I can't get the email back from the oauth endpoint and I can't seem to find the access_token to manually request user information. All I have is a "code" returned from the facebook login endpoint.

Here's the IdentityServer setup.

var fb = new FacebookAuthenticationOptions
            {
                AuthenticationType = "Facebook",
                SignInAsAuthenticationType = signInAsType,
                AppId = ConfigurationManager.AppSettings["Facebook:AppId"],
                AppSecret = ConfigurationManager.AppSettings["Facebook:AppSecret"]
            };

            fb.Scope.Add("email");

            app.UseFacebookAuthentication(fb);

Then of course I've customized the AuthenticateLocalAsync method, but the claims I'm receiving only include name. No email claim.

Digging through the source code for identity server, I realized that there are some claims things happening to transform facebook claims, so I extended that class to debug into it and see if it was stripping out any claims, which it's not.

I also watched the http calls with fiddler, and I only see the following (apologies as code formatting doesn't work very good on urls. I tried to format the querystring params one their own lines but it didn't take)

  1. (facebook.com)

    /dialog/oauth ?response_type=code &client_id=xxx &redirect_uri=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook &scope=email &state=xxx

  2. (facebook.com)

    /login.php ?skip_api_login=1 &api_key=xxx &signed_next=1 &next=https%3A%2F%2Fwww.facebook.com%2Fv2.7%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fidentity.[site].com%252Fid%252Fsignin-facebook%26state%3Dxxx%26scope%3Demail%26response_type%3Dcode%26client_id%3Dxxx%26ret%3Dlogin%26logger_id%3Dxxx&cancel_url=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%26state%3Dxxx%23_%3D_ &display=page &locale=en_US &logger_id=xxx

  3. (facebook.com)

    POST /cookie/consent/?pv=1&dpr=1 HTTP/1.1

  4. (facebook.com)

    /login.php ?login_attempt=1 &next=https%3A%2F%2Fwww.facebook.com%2Fv2.7%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fidentity.[site].com%252Fid%252Fsignin-facebook%26state%3Dxxx%26scope%3Demail%26response_type%3Dcode%26client_id%3Dxxx%26ret%3Dlogin%26logger_id%3Dxxx &lwv=100

  5. (facebook.com)

    /v2.7/dialog/oauth ?redirect_uri=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook &state=xxx &scope=email &response_type=code &client_id=xxx &ret=login &logger_id=xxx &hash=xxx

  6. (identity server)

    /id/signin-facebook ?code=xxx &state=xxx

I saw the code parameter on that last call and thought that maybe I could use the code there to get the access_token from the facebook API https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow

However when I tried that I get a message from the API telling me the code has already been used.

I also tried to change the UserInformationEndpoint to the FacebookAuthenticationOptions to force it to ask for the email by appending ?fields=email to the end of the default endpoint location, but that causes identity server to spit out the error "There was an error logging into the external provider. The error message is: access_denied".

I might be able to fix this all if I can change the middleware to send the request with response_type=id_token but I can't figure out how to do that or how to extract that access token when it gets returned in the first place to be able to use the Facebook C# sdk.

So I guess any help or direction at all would be awesome. I've spent countless hours researching and trying to solve the problem. All I need to do is get the email address of the logged-in user via IdentityServer3. Doesn't sound so hard and yet I'm stuck.

like image 841
Ryan Avatar asked Aug 26 '16 17:08

Ryan


People also ask

How do I use OAuth on Facebook?

Under Products in the App Dashboard's left side navigation menu, click Facebook Login, then click Settings. Verify the Valid OAuth redirect URIs in the Client OAuth Settings section. state . A string value created by your app to maintain state between the request and callback.

What is a Facebook access token?

An access token is an opaque string that identifies a user, app, or Page and can be used by the app to make graph API calls. When someone connects with an app using Facebook Login and approves the request for permissions, the app obtains an access token that provides temporary, secure access to Facebook APIs.

Where is client OAuth settings in Facebook?

In the App Dashboard, choose your app and scroll to Add a Product Click Set Up in the Facebook Login card. Select Settings in the left side navigation panel and under Client OAuth Settings, enter your redirect URL in the Valid OAuth Redirect URIs field for successful authorization.


1 Answers

I finally figured this out. The answer has something to do with Mitra's comments although neither of those answers quite seemed to fit the bill, so I'm putting another one here. First, you need to request the access_token, not code (authorization code) from Facebook's Authentication endpoint. To do that, set it up like this

        var fb = new FacebookAuthenticationOptions
        {
            AuthenticationType = "Facebook",
            SignInAsAuthenticationType = signInAsType,
            AppId = ConfigurationManager.AppSettings["Facebook:AppId"],
            AppSecret = ConfigurationManager.AppSettings["Facebook:AppSecret"],
            Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = (context) =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, ClaimValueTypes.String, "Facebook"));
                    return Task.FromResult(0);
                }
            }

        };

        fb.Scope.Add("email");

        app.UseFacebookAuthentication(fb);

Then, you need to catch the response once it's logged in. I'm using the following file from the IdentityServer3 Samples Repository, which overrides (read, provides functionality) for the methods necessary to log a user in from external sites. From this response, I'm using the C# Facebook SDK with the newly returned access_token claim in the ExternalAuthenticationContext to request the fields I need and add them to the list of claims. Then I can use that information to create/log in the user.

    public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx)
    {
        var externalUser = ctx.ExternalIdentity;
        var claimsList = ctx.ExternalIdentity.Claims.ToList();
        if (externalUser.Provider == "Facebook")
        {
            var extraClaims = GetAdditionalFacebookClaims(externalUser.Claims.First(claim => claim.Type == "urn:facebook:access_token"));
            claimsList.Add(new Claim("email", extraClaims.First(k => k.Key == "email").Value.ToString()));
            claimsList.Add(new Claim("given_name", extraClaims.First(k => k.Key == "first_name").Value.ToString()));
            claimsList.Add(new Claim("family_name", extraClaims.First(k => k.Key == "last_name").Value.ToString()));
        }

        if (externalUser == null)
        {
            throw new ArgumentNullException("externalUser");
        }

        var user = await userManager.FindAsync(new Microsoft.AspNet.Identity.UserLoginInfo(externalUser.Provider, externalUser.ProviderId));
        if (user == null)
        {
            ctx.AuthenticateResult = await ProcessNewExternalAccountAsync(externalUser.Provider, externalUser.ProviderId, claimsList);
        }
        else
        {
            ctx.AuthenticateResult = await ProcessExistingExternalAccountAsync(user.Id, externalUser.Provider, externalUser.ProviderId, claimsList);
        }
    }

And that's it! If you have any suggestions for simplifying this process, please let me know. I was going to modify this code to do perform the call to the API from FacebookAuthenticationOptions, but the Events property no longer exists apparently.

Edit: the GetAdditionalFacebookClaims method is simply a method that creates a new FacebookClient given the access token that was pulled out and queries the Facebook API for the other user claims you need. For example, my method looks like this:

protected static JsonObject GetAdditionalFacebookClaims(Claim accessToken)
    {
        var fb = new FacebookClient(accessToken.Value);
        return fb.Get("me", new {fields = new[] {"email", "first_name", "last_name"}}) as JsonObject;
    }
like image 126
Ryan Avatar answered Sep 28 '22 05:09

Ryan