How to authenticate users with facebook login in java

13,633

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.

Share:
13,633
TechChain
Author by

TechChain

I have 4+ of experience of overall experience.Currently working on Hyperledger Fabric blockchain framework. I have strong knowledge of Objective c, Swift.I have developed lot of apps from chat app, finance apps,location & map based apps.

Updated on June 04, 2022

Comments

  • TechChain
    TechChain almost 2 years

    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