Friday, February 14, 2014

How to retrieve Facebook profile using Apache Oltu

This tutorial shows you the basic of OAuth using Apache Oltu (Formely known as Apache Amber). We have created a Java Web Application that authenticates the user to Facebook via OAuth 2.0 and retreive the protected resources from Facebook.

Setup :
  • SSL enabled Tomcat Server as we have deployed our Web Application on tomcat. Click here for instruction on How to enable SSL on Apache Tomcat 7.0
  • Registered Facebook Application. Check here for instruction on How to register App on Facebook.
  • Download the OltuClientFB Application from the GIT repository.
  • If you are using Maven then add below dependency or download Apache Oltu client jars :
    <dependency>
      <groupId>org.apache.oltu.oauth2</groupId>
      <artifactId>org.apache.oltu.oauth2.client</artifactId>
    </dependency>

Run the Project :

Check out the project from the above URL, import into the eclipse and Run as a Server.

Navigate your browser to https://localhost:<port>/OltuClientFB. You will see the following page:





Click on the link and it will take you the Facebook page for Authentication :


Once you are login into Facebook, It will ask you to allow the Oauth application to access your private data:



Once you click on “Okay” button. It will display your profile detail like UserId, Name etc.



Code Description :

OAuthServlet.Java

In the Servlet initParams, We have defined the clientId, clinetSecret and the redirectUri, You can change it as per your Apps.
// clientId is 'App ID '
@WebInitParam(name = "clientId", value = "YOUR_CLIENT_ID"),
// clientSecret is 'App Secret'
@WebInitParam(name = "YOUR_CLIENT_SECRET", value = "70ba69525274876dce9697ad183a9051"),
// This must be identical to 'Valid OAuth Redirect URI's'
@WebInitParam(name = "redirectUri", value = "https://localhost:7443/OltuClientFB/OAuthServlet/callback"),})

The Java Web Application act as a third-party website or termed as “client” which operate on behalf of a user. It first sends the request to Facebook which authenticates the user, obtain the user's authorization(i,e Approve/Deny page) and issues an access token which client can use while interacting with the resource server i,e Facebook to access public profile of the user.

End user Authorization request :


Created the End User Authorization Request by providing end-user authorization URI at the Authorization Server (e.g. Facebook), application's client id and a redirect URI in order to receive the authorization code. Apache Oltu has an enum OAuthProviderType for authorization and token endpoints of common OAuth 2 providers like Facebook.

OauthClientRequest authClientRequest = OAuthClientRequest
.authorizationProvider(OAuthProviderType.FACEBOOK)
.setClientId(clientId).setRedirectURI(redirectUri)
.buildQueryMessage();

The above code will produce an OAuth request where all the parameters are encoded in the URL query.

response.sendRedirect(authClientRequest.getLocationUri());

Get Authorization Code from redirect URI :

Once the user grants permission for your client application, then the Facebook will redirects the user to redirectUri with the code in the request parameter.


OAuthAuthzResponse oar = OauthAuthzResponse.oauthCodeAuthzResponse(request); code = oar.getCode();

Exchange OAuth code for an access token :


Apache Oltu has two different classes to parse the access token response. Facebook’s response is not fully compliant with the final version of the OAuth 2 specification, but it can be parsed using the class GitHubTokenResponse.



OauthClientRequest authClientRequest = OAuthClientRequest.tokenProvider(OAuthProviderType.FACEBOOK)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(clientId).setClientSecret(clientSecret)
.setRedirectURI(redirectUri).setCode(authorizationCode)
.buildBodyMessage();
//create OAuth client that uses custom http client under the hood
oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(authClientRequest,
GitHubTokenResponse.class);
String accessToken = oauthResponse.getAccessToken();

Get Facebook profile data :

OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest("https://graph.facebook.com/me").setAccessToken(accessToken).buildQueryMessage();
OAuthResourceResponse resourceResponse oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET,
OauthResourceResponse.class);

DisplayFacebookProfile.Java 
This class will display the user profile on the UI.


Summary :

This application demonstrates the basic of OAuth 2.0 using Apache Oltu i,e how to authenticates the user and retreive the protected resources from Facebook.

Resources :

https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart

Code download link:
https://drive.google.com/file/d/0B7WKU816EmtaSUw3UmpsWUljWk0/view?usp=sharing

12 comments:

  1. Hey great post! Can you post the link to your github source? I am trying to build a Oauth2 client in java and am new to the server world would love to see a full example.

    ReplyDelete
    Replies
    1. Hey sorry for the late reply. I have not uploaded on githubs but I have zipped it for you, just download it from here(http://www.4shared.com/rar/0Njd4RC0ce/OltuClientFB.html), import into Eclipse, change the Id,Secret and Run the application as Server.

      Let me know if you get any issue.

      Delete
  2. can u pls activate http://www.4shared.com/rar/0Njd4RC0ce/OltuClientFB.html for me?

    ReplyDelete
    Replies
    1. Hey could you share me your email ID. I ll send you as zip.

      Delete
  3. Your code is not downloadable. Could you please upload the code on github repository. It will be worth for all your followers.

    ReplyDelete
    Replies
    1. Hey could you share me your email ID. I ll send you as zip.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. This comment has been removed by the author.

      Delete
    4. This comment has been removed by the author.

      Delete
    5. I guess, You don't required all such parameters to Integrate with Google, It will work in the same fashion as you have done with Facebook. Chek here for more details : https://developers.google.com/google-apps/calendar/instantiate

      Delete
    6. This comment has been removed by the author.

      Delete
  4. I have pushed the code on Google Drive :
    https://drive.google.com/file/d/0B7WKU816EmtaSUw3UmpsWUljWk0/view?usp=sharing

    ReplyDelete

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...