OAuth 2.0 Security workflow

SECURITY (using OAuth 2.0)

 

Security is essential to any web application. In CE Hub,  we have taken all possible measures to make the application secure. We are implementing spring security and OAuth 2.0 standards. Each request trying to communicate with the HUB must pass through the security layer of the application.

TD-CEHub-Communication

Fig 1. explains the communication between CE Hub and the different channels/devices.

There are three layers of security implemented:

  1. Authentication – The authentication is validating the user credentials. Only the users registered to the application can login providing their valid credential.
  2. Tenant verification – This layer verifies if the requesting user belongs to the tenant for which he/she is requesting the resources from. This restricts user from one customer/organization accessing other customers data.
  3. Authorization – Authorization means checking if the user is authorized to perform the requested task.              

Fig 1. The flow of requests and response through the security of the application.

The figure is explained below.

Explanation:

  1. The HUB is protected by the security layer (The portion in green background), which means any communication into or out of the hub must pass through the security layer.
  2. At first the any requesting client must provide his/her authentication credentials to get inside the authentication layer.
  3. After authentication the OAuth will provide Refresh token and Access token which will be used to access the next layer of the security that is authorization layer. (More about OAuth 2.0 in the section 2 below).
  4. In the authorization layer a particular user will be provided a grant and some role which will decide what all activities he/she can perform in the HUB.
  5. After passing through the Authorization layer there is a Tenant verification layer, which will validate if the user belongs to the requested tenant or not. (More about multi tenancy explained in section 3 below.)

 

  1. OAuth 2.0

      1.(a). Flow of OAuth 2.0 security

Flow security

Fig. 2. OAuth 2.0 flow diagram for explaining the security flow.

Here is a more detailed explanation of the steps in the diagram:

  1. The application requests authorization to access service resources from the user
  2. If the user authorized the request, the application receives an authorization grant
  3. The application requests an access token & refresh token from the authorization server (API) by presenting authentication of its own identity, and the authorization grant
  4. If the application identity is authenticated and the authorization grant is valid, the authorization server (API) issues an access token & Refresh token to the application. Authorization is complete.
  5. The application requests the resource from the resource server (API) and presents the access token for authentication
  6. If the access token is valid, the resource server (API) serves the resource to the application
  7. If the access token expires after a certain period of time, we can re-issue the access token using the refresh token so that the username and password doesn’t need to be provided at each authentication process.

The actual flow of this process will differ depending on the authorization grant type in use, but this is the general idea. We will explore different grant types in a later section.

1.(b). User Details

The user details are stored in the database in the USER table which is related to ROLE and RIGHT in separate tables, so that a particular user can only perform activities which are permitted to his role and right only. The password is stored in BCrypt encryption format which uses a brute force method to encode the passwords, and most important is the bcrypt does not have any method which allows decoding the password, so nobody can ever decode the secure passwords.

1.(c). Application Registration

Before using OAuth with our application, we must register your application with the service. This is done through a registration form in the “developer” or “API” portion of the service’s website, where you will provide the following information (and probably details about your application):

  • Application Name
  • Application Website
  • Redirect URI or Callback URL

The redirect URI is where the service will redirect the user after they authorize (or deny) your application, and therefore the part of your application that will handle authorization codes or access tokens.

1.(d). Client ID and Client Secret

Once your application is registered, the service will issue “client credentials” in the form of a client identifier and a client secret. The Client ID is a publicly exposed string that is used by the service API to identify the application, and is also used to build authorization URLs that are presented to users. The Client Secret is used to authenticate the identity of the application to the service API when the application requests to access a user’s account, and must be kept private between the application and the API.

1.(e). Authorization Grant

In the Abstract Protocol Flow above, the first four steps cover obtaining an authorization grant and access token. The authorization grant type depends on the method used by the application to request authorization, and the grant types supported by the API. OAuth 2 defines four grant types, each of which is useful in different cases:

  • Authorization Code: used with server-side Applications
  • Implicit: used with Mobile Apps or Web Applications (applications that run on the user’s device)
  • Resource Owner Password Credentials: used with trusted Applications, such as those owned by the service itself
  • Client Credentials: used with Applications API access

Now we will describe grant types in more detail, their use cases and flows, in the following sections.

1.(f). Grant Type: Authorization Code

The authorization code grant type is the most commonly used because it is optimized for server-side applications, where source code is not publicly exposed, and Client Secret confidentiality can be maintained. This is a redirection-based flow, which means that the application must be capable of interacting with the user-agent (i.e. the user’s web browser) and receiving API authorization codes that are routed through the user-agent.

1.(g). Example Access Token Usage

Once the application has an access token, it may use the token to access the user’s account via the API, limited to the scope of access, until the token expires or is revoked.

Here is an example of an API request, using curl. Note that it includes the access token:

curl -X POST -H “Authorization: Bearer ACCESS_TOKEN“”https://localhost:8080/ceapi/v2/$OBJECT

Assuming the access token is valid, the API will process the request according to its API specifications. If the access token is expired or otherwise invalid, the API will return an “invalid_request” error.

1.(h). Refresh Token Flow

After an access token expires, using it to make a request from the API will result in an “Invalid Token Error”. At this point, if a refresh token was included when the original access token was issued, it can be used to request a fresh access token from the authorization server.

Here is an example POST request, using a refresh token to obtain a new access token:

https://localhost:8080/ceapi/oauth/token?grant_type=refresh_token&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&refresh_token=REFRESH_TOKEN

1.(i). Token Store

We store all the tokens generated by the security process in the database so that even there is a system failure or un planned power shut-down the tokens generated will be available and they can be accessed after the system power gets restored.

Following are the six tables being used by the OAuth 2.0

  1. OAUTH_ACCESS_TOKEN
  2. OAUTH_APPROVALS
  3. OAUTH_CLIENT_DETAILS
  4. OAUTH_CLIENT_TOKEN
  5. OAUTH_CODE
  6. OAUTH_REFRESH_TOKEN

Some important tables are described below:

OAUTH_CLIENT_DETAILS contains the information related to access token and refresh token expiration time.

OAUTH_ACCESS_TOKEN stores all the access tokens.

OAUTH_REFRESH_TOKEN stores all the refresh tokens.

The tokens stored in the database are in encrypted format and are impossible to decode so even if someone gets access to database he/she can not get through the security of the application. The tokens are extrapolated to longblob format and uses bcrypt encryption policy.

2. Multi Tenancy

multy tenancy

Fig. 3. Fine grained multi tenancy applied in the application to segregate tenant data from each other.

 

The above diagram explains that despite of having the same physical resource fo the tenant management we have separated the data of one tenant from another using the domain name and tenant id.

Every data in the database will be associated with a tenant id so that we can identify to which tenant the data belongs.

multi 2

Fig. 4. Is the explanation of how one physical resource is separated from various tenants.

Fig. 4. This is how the virtual separation of single resource i.e. the HUB looks like.

As the HUB will be accessed by different clients we have also included the multi tenancy feature in the application. By including this a user from one tenant will not be provided grant to access other tenant’s resources.

 

In our context the tenant can be considered as a client or company,

Following is an example of the tenant feature:

 

Lets consider the following URL’s

https://www.company1.com/get-all-billofladings

https://www.company2.com/get-all-billofladings

 

In the above two example urls we can notice that we have company1 and company2 as the tenant identifiers.

 

We are using URL’s to identify tenants

In the above example the users of tenant1 will not be able to access the resources of tenant2 and viece versa. And if any user of tenant1 tries to access the resources of tenant2 he will be restricted to do so with 401 UnAuthorized response status and an error message.

To achieve this we are having a field called tenant in each table in the HUB which will separate the one tenant’s data from another.

By this architecture we can guarantee that we have the data related to one company secured from another company in database level.

Feedback/Comments are welcome

Thanks,
Kalyan

 

 

Enable JPA Tools in Eclispe

Hello Guys..

Sometime we need to generate entities from the database table or vice versa. Off course we can do it manually, but that is huge time consuming process.

In those situations, JPA Tools comes into action and plays a handy role creating the entities from already existing the database. How can we do that in our project.

  1. Convert the project into JPA Project. (Right click on project -> configurations -> convert to JPA Project)
  2. Once converted, again right click on the same project and you will see a “JPA TOOLS” in the context menu options.
  3. There you will see “Generate tables from entities” and few more options.

Now if you are using STS, you will wonder why you can not convert the given project to JPA project. In fact the option in configuration is missing itself. Then how can we convert the project??

Continue reading

Java Eclipse/STS Tips | Disable formatting for specific section

Sometimes which is a necessary and we get habituated off using that more often then not may cause an undesirable effect. Confused?

Let me give you an example of how a frequently used practise possess issues.
Consider “formatting” (CTRL + SHIFT + F), this has been one of the favourite combination for all eclipse users .

If you are a java or spring developer, then you might have figured it out… right ?

No? No issues .. In Java when we use streams and we intentionally break steps  of the chain logically. But if we intended Eclipse to format all the codes in that .java file, it do not understands our logical breaking and brings everything to one line. Also Spring developers might have faced it during Security Configurations with HTTP chaining.

Before formatting

List persons = new ArrayList();
String name = persons.stream()
		.filter(x -> "sovan".equals(x.toString()))
		.map(String::toLowerCase)						
		.findAny()
		.orElse("");

After formatting

List persons = new ArrayList();
String name = persons.stream().filter(x -> "sovan".equals(x.toString())).map(String::toLowerCase).findAny()
				.orElse("");

Is there a way we can stop formatting for this section of code?

Yes!!!

This feature is there only inside our developer tool.. Hidden secret!! HUH!!
Now let this secret revealed..

  • Go to Windows -> Preferences -> Java -> Code Styling -> “Formatter”
  • Click on Edit on the details section. (You can create your own development profile)
  • In the edit section, choose “On/Off tags”.
  • Check “Enable Off/On Tags”. Leave the default @formatteroff and @formatteron or you can rename the tags.
  • Done. Save your profile.

    This slideshow requires JavaScript.

Now wrap your codes around these off and on tag and eclipse will leave that section  untouched while formatting rest of the code.

If you like this post and is helpful, please do leave a comment below. If anyone knows any other better way of doing this, please do share.

Helps the community grow by sharing knowledge.
Happy Coding
Sovan

 

Java 8 – Default Methods in Interface

Java 8 arrived with new features and advances which has also interface with default methods in its arsenal too.

What we might have heard about default methods in interfaces?

  • Multiple inheritance.
  • Backward Compatibility.
  • Default methods reduces the need of abstract class.

While the first two points are correct but the last point is not though it seems to more or less works like the abstract class. I will keep it for last, and starts with some basic information.

Why we needed Default Methods inside Interface?

As it is said, when there are problems we look around for solutions , this is the case where it get fits. Think of a situation where one needs to declare a new method signature inside an interface, and that interface has been implemented in 100’s of classes.  Hhhuh!! That is a painful task as first it is mandatory to  implement it all the the new method in 100 instances and also we need to handle the situation where we don’t need that function.

What if we are allowed to write a default method definition inside interface?
Listen behind, someone whispering “Java 8 allows you to do so…

Continue reading

@ConfigurationProperties : Spring Boot’s way of handling properties

Hello coders,

 

We are always in quest of improving something or the other in our lifetime, this urge also fits in for technologies as well. We can see many enhancements and updates on each and every technology so as in our favourite Spring Framework.

Spring has come a long way ahead since its inceptions.. Yes, the latest buzz word is “SPRING BOOT”!! Though it has made a lot of things easier for a developer, but sometime it debatable. In a nutshell, understanding it deeply is a must.

Here, I will be sharing a tiny, may be a tiniest of a configuration annotations @ConfigurationProperties 

We must have used properties files in almost all of our applications. Spring Boot provides a clean and neat way of using it in applications. Instead of writing the long properties name which is very error-prone (we must have spent lot of time debugging and at last it just a spelling mistake of property name).

So, how about creating a class that gets mapped to properties on a file? Isn’t it a neat style?

Let’s get into coding. We used to start with writing the properties first, but here we can start designing a properties in a Class then move to properties file.

Create a class:

package com.pack.subpack.utils.properties;

import java.util.List;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix="jwt")
public class JwtProperties {

    private String header;
    @NotNull
    private String secret;
    private int expiration;
    private Map <String,String> authorisation;
    private List<String> someProperties;


//... Getters & Setters
}

This class is marked as @Component. Which makes it a candidate for @Autowiring. Also we have used @ConfigurationProperties(prefix=”jwt”), which indicates that this will get mapped to all properties starts with jwt. Lets have an look at the properties file (properties.yaml)

jwt:
  expiration: 604800
  path: auth
  secret: secret
  authorization:
  username: sovanm
  salt: mysecr3t
  some-properties:
    - prop1
    - prop2

Now the mapping is done, but how to use it? This must be simple. Yes you guessed it right. It is simple. Just Inject the Component and enjoy the get methods to get the values.

private JwtProperties jwtProperties;
// Constructor Injection
@Autowired
public JwtTokenUtils(JwtProperties jwtProperties) {
    this.jwtProperties = jwtProperties;
    System.out.println("Secret: " + this.jwtProperties.getSecret());
    System.out.println("SomePropertiesList: " +
           this.jwtProperties.getSomeProperties());
    this.jwtProperties
        .getAuthorization()
        .entrySet()
        .stream()
        .forEach(e-> {
             System.out.println(e.getKey() + " : " + e.getValue());
        });
}

Done! we can now use the properties anywhere in this class. It helps to make our work easier as we all love to use object intelligence rather than writing the string version as

@Value("$(jwt.authorisation)")
private Map authorisations;

Features, that we can take advantages are:

  •  We can use JSR-303 Annotations for validations. (E,g: Used above)
  •  Intelligence available in the properties file.
  • We can load family of properties into separate classes using the appropriate prefix.

There are lots to know..but  I hope, this might help you getting started dealing with properties file in Boot’s way.

Thanks for reading and Happy Coding 🙂

Sovan

Let us start the SPRING…

Hello Again..

It’s coding time now…and let us do some JAVA coding first then we will “Springify” that code using Spring Framework. It is a simple Java program with classes, interface, main class to bring together all classes to work as one application.

What will we do….

I know you guys will be sad because I promise to have some spring codes, but trust me staring with Springs right away will not that interesting…

Some Prerequisite…

  • IDE : I will be using STS. (SpringSource Tool Suite).
  • Knowledge of Java
That’s it for now..
Begin….
Let us create a simple Contact Manager Application.
  • Create a Java Project (File -> New -> Java Project)
  • Create a Package “com.springwelcome.model” and inside that create a class “Contact.java“. Here we are going to define what we need to store in as contacts. It is a simple POJO class with FirstName, LastName and PhoneNumber.
  • Let us now create another package that will contains the method dealing with data for Database Transactions. Here we are not going to use any database instead we will be using List to store information and return to our Service class. 
  • For this create a package “com.springwelcome.repo” and add a new class “AddToContactImplementation.java“. You must be wondering why am I used …Implementation. Yes, I will using an interface. Let me add the code to make it clear. 

  • Here the question arises why are we using interface here, where we can use the class name directly while creating the instance. You are absolutely correct. In future we are going to learn about spring and we are going to convert this application using springs. In Spring we have an important concept “Inversion Of Control”. Lets move into this later….
  • As we have the Data Storage Class A.K.A. DAO (Data Access Object). To know more about  DAO please follow the link. Now let us create the service which will return us the names in the contact. 
  • Let me create a new package and name it as “com.springwelcome.service” and create a new class inside it as well and name it as “ContactService.java“. 
  •  Similarly we will be implementing an interface here as well. 

  • Now we are almost done with all the parts of this application, We just need to bring together all parts into one. Let us create a new class without any package and name it “ContactManagement.java“. This will contain the  entry point for out application. the MAIN class. 

That is it..we are done with a java application which will be SPRINGIFY soon..

    Hoping you get along with this easily…till next time when we will be doing some changes to implement springs…
    Happy coding.. 🙂

    Thanks,

    Sovan

    … Why SPRING ??

    Hello Guys,

    As already mentioned, Spring is very lightweight and to make it more light it runs on a web container like Tomcat, and to make it lighter for developers it simply based on POJO (plain old Java objects). Even one can create a simple application with simple POJO and some spring configurations.

    Springs came to picture as an alternative to the existing Java EJBs due to the fact that EJB applications has huge problem while maintaining, lack for testing functionalists takes away the first and strong line of defense from developers, adding and removing modules into the old application was very very difficult as they are tightly coupled with each others. With these the added pressure of dealing with the complexities in code do not let developers to concentrate on the core business logic.

    Springs provide greats solutions to all these problem…

    • Testability
    • Maintainability
    • Scalebility
    • Handling complexities with ease
    All together, these makes our life easier and force us to fall in love with SPRINGS at first place. We can now concentrate more on the development of application with the business on mind not with the complexities of coding. We can now handle the exceptions while it still in making not at a point where it became a monster and start punching and kicking us with powerful exceptions. 
    From requester’s perspective, when they need something and ask for that they want that need as final product not the steps followed to make it or make it safe or make it better. On this SPRINGS becomes a huge relief for us to provide requester what they need.
    Now aren’t you in LOVE with spring ? I am now for sure as I am sailing ahead and much interested to get into it ASAP. I know you too and want to see some codes. For us life without codes are boring.

    I promise in coming series will try to get started with our first application…

    Thank you,
    Sovan Misra