Pages

Subscribe:

Ads 468x60px

Featured Posts

Friday, August 10, 2018

Drools - How we overcame the drastic conditions evaluation


One year ago, we started a project called keystone, a rules evaluation engine based on spring-boot. The high level architecture as follows [1]. It exposes several REST endpoints to evaluate some business rules. When a request hits the engine, several parallel calls hit the described endpoints based on the input parameters. ( We use RxJava to handle the async calls and zip out the results.) Then we have various IF ELSE blocks to evaluate the rules. And sent back the results back to the client after the rule evaluation.


At the beginning the rules were quite simple and everyone was happy with the architecture and the evaluation of the rules. There was a manageable number of rules with simple if else blocks, and the changes to existing rules were quite minimum at that time.

But when time passed by, there were many requests from partner teams and the rules engine team was asked to implement more logical evaluations, so new REST endpoints were introduced. Now the problem became more complex and hard to manage the rules in our code as well as presenting the rules. When some business users ask what happens if we use the REST endpoint X, we have no way to easily explain all the conditions and evaluation paths in a simple manner.

Then the drools comes into the picture to address this problem. We evaluate the drools and did POC for both the drl file and decision table approaches. The code becomes much more simpler and lean since all the evaluation tree was derived from the decision table. Then we presented both the drl file and decision table to the business people and they were really admired the decision table approach since it became more easy to present to other partner teams.
See below for an example decision table which is being used. It contains 10 decision points before the evaluation.



Let’s look into a sample which use a decision table to evaluate some rules. 


Sample use case.
We are going to evaluate the loan rate given by ABC bank depending on the customer is a GOVERNMENT or a PRIVATE worker and currently a retired person or not. Decision table for the above scenario is as follows.



Decision table for the above use case.


Maven dependencies.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-core</artifactId>
            <version>7.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.kie</groupId>
            <artifactId>kie-spring</artifactId>
            <version>7.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-decisiontables</artifactId>
            <version>7.0.0.Final</version>
        </dependency>
Load the Configurations
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public KieContainer getKieContainer() {

        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        kieFileSystem.write(ResourceFactory.newFileResource(drlFile));
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();
        KieModule kieModule = kieBuilder.getKieModule();

        KieContainerkieContainer =  kieServices.newKieContainer(kieModule.getReleaseId());

        return kieContainer

}


We use the ExecutionBase class to hold the facts and the conditions. Fact is of course the Customer object and isGovernmentWorker() and is Retired() conditions.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class ExecutionBase {

    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public boolean isGovermentWorker() {
        return this.customer.getWorkType().equals(WorkType.GOVERNEMNT);
    }

    public boolean isRetired() {
        return this.customer.getAge() &gt; 60;
    }

    public void execute(String result) {
        System.out.println(result);
    }
}


After the execution we get the entitlement loan rate for a bank customer. Try out the sample code link.



To summarize the post, we discussed how we can leverage the drools decision tables to overcome if there are drastic conditions evaluations in your program and you want to change those conditions without touching the code. Other advantage is the decision table can be used as a tool to describe your execution flow for non technical people. That’s it for this post and hope to see you in another exciting post.

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.