Pages

Subscribe:

Ads 468x60px

Featured Posts

Monday, September 25, 2017

oauth2 implicit grant flow - example using facebook oauth2 API

In this post we are going to explore on the oauth2 implicit grant flow using a facebook oauth2 API example. In the oauth2 client specification, the clients are categorized as trusted and untrusted.
Trusted oauth2 clients
Trusted oauth2 clients are usually application following the mvc architecture, where the application has the facility to store the keys securely. In a later post we will explore more on trusted oauth2 clients. 
Untrusted oauth2 clients
Pure html / javascript applications are considered as untrusted oauth2 clients. These applications typically don’t have a way to securely store information. Typically these applications need to initiate the authorization flow for each session.


Normal flow of an untrusted oauth2 client.

Implicit grant flow - sample usecase



The above example use case is for a Travel Buddy App, which needs user’s facebook friend list to suggest the user travel buddies.

  1. User requesting the Travel Buddy App to suggest him more friends.
  2. Travel Buddy App, says, sure I can do that, but first goto this url and authorize me.
  3. Travel Buddy App redirect to facebook Consent Page and presented with a authorization confirmation page with list of scopes.
  4. When user, says yes, redirect to the Travel Buddy App with a token to use.
  5. Travel buddy app initiate a request to get the friend list from facebook, presenting the token received in the previous step.
  6. Travel Buddy app receives the friend list.

So let’s implement this.

I assume you have a facebook account and first you need to register this Travel Buddy App with facebook. Then you’ll receive a client_id for your application.

Facebook settings.
  1. Login to facebook and go to https://developers.facebook.com/
  2. Click on Add a New App and provide a display name and contact email. Click Create App ID.
Screenshot from 2017-09-25 12-01-03.png

  1. Then you’ll redirected to following dashboard with App Id and App Secret.

Screenshot from 2017-09-25 12-06-57.png

  1. Now select Add Product and select Facebook Login, click setup.
add-product.png

  1. Choose platform web, fill out the details and save.
  2. Go to Products -> Facebook Login -> Settings, Add the Valid OAuth redirect URIs, in our sample it is, http://travelbuddyapp.com:8080

oauth.png


Now all set from facebook settings.

Let’s move on the Travel Buddy App implementation.

  1. Need to create a simple web skeleton. You can use the following maven archetype.

mvn archetype:generate -DgroupId=com.sample -DartifactId=travel-buddy-app -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

  1. Remove the index.jsp file, since we are implementing a simple html js application.
  2. First we have to write the getting the token function. We have to make  a GET request to dialog/oauth endpoint with the following details.
    var facebookAuthEndpoint = "https://www.facebook.com/v2.10/dialog/oauth";
    var responseType = "token";
    var clientId = "118592235486459";  
    var redirectUrl = "http://travelbuddyapp.com:8080/callback.html";
    var scope = "public_profile user_friends";
    
  1. Since we are  s the application to redirect, we have to provide the redirectURL. The scope is the permission list we are requesting from the user. In this case we need public_profile and user_friends.
Note that the permission list in scope variable is given a space separated list.
  1. The calling URL will be similar to the following, Note that the url parameters needs to be encoded.
https://www.facebook.com/v2.10/dialog/oauth?response_type=token&client_id=118592235486459&redirect_uri=http%3A%2F%2Ftravelbuddyapp.com%3A8080%2Fcallback.html&scope=public_profile%20user_friends

  1. Then after redirecting to facebook website, if the user is already logged in, he will be presented a user consent page. If not first redirected to the login page.
  2. After the authorization of the user, will be redirected with the token appended to the browser URl. Process the browser URl and acquire the access_token.

var fragment = location.hash.replace('#', '');

  1. Then we have to make two API GET calls to facebook using this access token.

I. Make a call to get the profile details and extract the profile ID.
II. Make another call to get the suggested friend list using that profile ID.

       var userEndpoint = "https://graph.facebook.com/v2.10/me?fields=name&access_token="  
                                                                    + accessToken;
       var userId = "";
       //ajax GET call to get user ID
       $.get(userEndpoint, function(data, status){
           userId = data.id;
           var friendListEndpoint = "https://graph.facebook.com/v2.10/" + userId + 
     "/friends?access_token=" + accessToken;

           $.get(friendListEndpoint, function(data, status){
                 $("#response").html(JSON.stringify(data));
           });
       });          

  1. We just showing the friend list appended to the html.

Now that’s it, you have acquired oauth2 token using the implicit grant flow approach and use that to extract the friend list.

Testing the Application.

  1. Set the following host entry.
127.0.0.1    travelbuddyapp.com
  1. Deploy the webapp in tomcat and access the following url.
http://travelbuddyapp.com:8080/
  1. Click the Call Facebook
  2. And you’ll get the friend list data.

So we have covered the implicit grant flow and the few characteristics we observed is that, it’s pretty straightforward to implement. And the negative points to be considered are approach is considered as to be less secure since we are exposing the access token, this is a short term access methodology, Since there is no way to securely store the keys, the authorization flow has to be reinitiated for latter use. Sample code can be found here. 

Let’s meet with a new blog post on oauth2 authorize grant flow exercise.

Tuesday, February 7, 2017

Functions as First Class Citizen Variables

Hello all, In this post we are going to talk about functions as first class citizens and it's usages.
taken from - https://www.linkedin.com/topic/functional-programming
The easiest way to understand is to analyze a demonstration. Package java.util.function  in java 8 contains all kinds of single method interfaces. In this samples we are going to use the java.util.function.Function and java.util.function.BiFunction interfaces.

1. Create  an inline lambda expression and store in a variable.
BiFunction<Integer, Integer, Integer> addFunction = (int1, int2) -> {
            return int1 + int2;
        };

to call the above method we can do as follows.

addFunction.apply(100, 200);

2. Create a static method that fits into the signature of the BiFunction interface, then assign it to the variable and invoke.

import java.util.function.BiFunction;

/**
 * Created by aruna on 2/7/17.
 */
public class Main {

    public static void main(String[] args) throws Exception {
        //create the variable
        BiFunction<Integer, Integer, Integer> addFunctionVariable;
        //assign the function to variable
        addFunctionVariable = Main::addStaticFunction;
        //invoke
        addFunctionVariable.apply(100, 200);
    }

    private static int addStaticFunction(int int1, int int2) {
        return int1 + int2;
    }
}

3. Create a instance method that fits to the signature of the BiFunction interface. In this approach, first we have to create the instance to acquire the function variable.

import java.util.function.BiFunction;

/**
 * Created by aruna on 2/7/17.
 */
public class Main {

    public static void main(String[] args) throws Exception {
        //create the variable
        BiFunction<Integer, Integer, Integer> addFunctionVariable;
        //create Main Object
        Main main = new Main();
        //assign the instance method to variable
        addFunctionVariable = main::addFunction;
        //invoke
        addFunctionVariable.apply(100, 200);
    }

    private int addFunction(int int1, int int2) {
        return int1 + int2;
    }
}

Now take an example, how to pass functions as variables and do some stuff.

import java.util.function.Function;

/**
 * Created by aruna on 2/7/17.
 */
public class Main {

    public static void main(String[] args) throws Exception {

        //define a function that multiply integer by 100
        Function<Integer, Integer> function = (intValue) -> { return intValue * 100;};
        //pass that function as a variable
        multiplyAndAdd(100 , 200, function);
    }
    private static int multiplyAndAdd(int int1, int int2, Function<Integer, Integer> function){

        if(function != null) {
            int1 = function.apply(int1);
            int2 = function.apply(int2);
        }

        return int1+ int2;
    }
}