How to authenticate users with facebook login in java

TechChain picture TechChain · May 9, 2014 · Viewed 13.3k times · Source

Hi i am working on a web project using java i want to user of website to log in using their Facebook account.I tried Facebook Developer official

but didn't get the solution

Answer

Leos Literak picture Leos Literak · May 9, 2014

I can recommend you OAuth library Scribe, or its improved fork Subscribe. If you are interested in usage samples, take a look at my project OAuh JEE Login.

First you need to get OauthService instance:

OAuthService service = new ServiceBuilder()
            .provider(FacebookApi.class)
            .apiKey("key").apiSecret("secret")
            .scope("email").callback("https://hostname/endpoint/")
            .build();

Then you need to redirect user to facebook page where he will grant access to your application / log in:

String redirectUrl = service.getAuthorizationUrl(NULL_TOKEN);
response.sendRedirect(redirectUrl);

Facebook will then call your callback uri and you need to grab parameter code and get access token:

String verifierValue = request.getParameter("code");
if (verifierValue == null) {
    log.warn("Callback did not receive code parameter!");
    return false;
}

Verifier verifier = new Verifier(verifierValue);
Token accessToken = service.getAccessToken(NULL_TOKEN, verifier);

Finally it is time to use this token to ask Facebook for user details:

OAuthRequest resourceRequest = new OAuthRequest(Verb.GET, RESOURCE_URL);
service.signRequest(accessToken, resourceRequest);
Response resourceResponse = resourceRequest.send();

JsonObject jsonObject = JsonObject.readFrom(resourceResponse.getBody());
JsonValue value = jsonObject.get("username");

See the class FacebookOAuthProcessor.