What can you use when you’ve to let the access of protected resources by a third part application? The Open Authentication standard (briefly OAuth) is useful in order to authenticate and authorize user credentials from an external application and grant the access of your resources.
The Open Authentication is a standard defined by the RFC (Request For Comments) number and is used when we’re not in common scenario to be the system application and the system validator and we’ve everything under our control.
We’re in the scenario when the application who consume the resource (consumer) is not the same which hold the information (server). Let me show it by using a graph.
The client access to his application (1) and makes the request to be grant to access a protected resource (2). The Authentication Server returns an access token based on the posted user credential (3). Afterward, the user makes the request passing the access token just got by the user (4). Once the token is validated, the Resource Server returns the protected resource to the Client Application (5).
Quite easy, isn’t it? Take a look at sequence diagram to clarify the concept above.
The client request contains the user and the client credential. We use the “grant_type=password” to send the user credential. The standard accepts four types of grant_type (authorization_code, password, client_credentials and refresh_token); more details are available on reference page.
So, if the Authentication Server validates the credential, it returns the access token composed by the access token itself, the token type, the expires date of the token and the refresh token (we’ll see the use of that later).
Using the access token in the header, we can access the protected resource from the Resource Server.
What happens when the token expires? Well, you get the message “invalid_token” but we can get another valid token using the refresh_token and changing the “grant_type” in “refresh_token”.
Have a look at the sequence diagram.
Once the user get the new access token, the process goes on as normal described in the first diagram.
Now, it’s time to take a look at some code. Before starting I’ve to say that is useful to be familiar with Spring Security to understand all the configuration blocks because Spring OAuth 2.0 is based on Spring Security. We’ve a system with 2 Rest.
The first is for getting and refreshing the access token (/oauth/token). The second is for accessing the protected resource (/protected/userresource/userprofile).
The core of the system is the spring configuration file.
<?xml version="1.0" encoding="UTF-8" ?>
eset endpoint security 5 offline update endpoint security 10