Search code examples
springfacebookspring-mvcfacebook-graph-apispring-social

Get email associated with FB account while handling callback from Facebook


Consider following scenario:

  • I want to support both ways to authenticate user in my application (using email/password and using FB account).
  • A user signed up to my application using email ([email protected])
  • Later he tries to sign in using his FB account (which btw. has the same email address he used to sign up using email/pwd)

According to this tutorial, handling the callback from Facebook while signing in should look like below (and it works perfectly fine):

@RequestMapping("/auth/facebook/callback")
public RedirectView callBack(@RequestParam("code") String code,
                             @RequestParam("state") String state,
                             HttpSession session) {
  String stateFromSession = (String) session.getAttribute(STATE);
  session.removeAttribute(STATE);
  if (!state.equals(stateFromSession)) {
    return new RedirectView("/login");
  }

  AccessGrant accessGrant = getAccessGrant(code);

  String facebookUserId = getFacebookUserId(accessGrant);
  session.setAttribute("facebookUserId", facebookUserId);
  return new RedirectView("/logged-in");
}

Question The question is, how can I determine by facebook user id, that I already have a user with such an email in my database, since I know only the FB user id and I don't know his authentication token to retrieve the email using FB graph?

Goal I hope my question is clear. What I try to achieve is to associate the user account that he created by signing up using email and password with his FB account, to provide him an additional option to sign in to my application.


Solution

  • Oh, I just found the answer by myself. The AccessGrant has a method that returns accessToken

    accessGrant.getAccessToken()
    

    Now I can call the FB graph using FB user id and access token to get the email (assuming that user granted me permission to fetch his email).