May 05, 2020

#SpringSecurity: OAuth2 Implementation with Spring Boot

In this tutorial we will learn to build an authorization server using oauth2 to authenticate user's identity to provide access_token. This access_token will be used to request data from resource server.

We will be creating an authorization server and embedding the resource server inside authorization server. Authorization server will generate the tokens and resource server will validate these token.

We will be having two services, first one would be authorization server (along with resource server) and the second one would be a client, from which we will be accessing the servers.

Create an OAuth 2.0 Server

GIT URL: OAuth 2.0 Server

Let's create a Spring starter project with name 'spring-security-auth-server'.
  • Type: gradle
  • Group: com.khs.oauthclient
  • Artifact: spring-security-auth-server
  • Dependencies: Web(spring-boot-starter-web), Oauth(spring-security-oauth)
We need to add some properties in src/main/resources/application.properties. These properties will set the server port, servlet context path, and some default values for the in-memory, ad hoc generated tokens the server is going to return to the client, as well as for our user’s username and password (in our case both username and password is admin). In production, we need to remove the hard-coded redirect URIs and usernames and passwords.
  • server.port=8081
  • server.servlet.context-path=/auth
  • user.oauth.clientId=R2dpxQ3vPrtfgF72
  • user.oauth.clientSecret=fDw7Mpkk5czHNuSRtmhGmAGL42CaxQB9
  • user.oauth.redirectUris=http://localhost:8082/login/oauth2/code/
  • user.oauth.user.username=admin
  • user.oauth.user.password=admin

Now we need to annotate our SpringSecurityAuthServerApplication.java with @EnableResourceServer. FYI, @EnableResourceServer annotation enables our Spring boot application to work as a Spring Oauth2 resource server.

Create a new package com.khs.oauthclient.config. Inside this package create a class with name AuthServerConfig, this class will extend AuthorizationServerConfigurerAdapter. We need to annotate this class with @Configuration @EnableAuthorizationServer.

FYI, @EnableAuthorizationServer annotation creates an authorization server with an in-memory repository to store client tokens and provide clients with a username, password, client id and secret. @EnableResourceServer annotation is used to access tokens.

The AuthServerConfig class is the class that will create and return our JSON web tokens when the client properly authenticates.

We will override configure method which takes ClientDetailsServiceConfigurer, we will hard-code client id, client secret. Authorization Grant will be set as authorization_code and scope will be user_info.

We will override another configure method which takes AuthorizationServerSecurityConfigurer as input.

After this we will create SecurityConfiguration class inside com.khs.oauthclient.config package. This class will actually authenticates requests to your authorization server. It will extend WebSecurityConfigurerAdapter and will be annotated with @Configuration and @Order(1).

FYI, @Order annotation defines the sorting order of an annotated component or bean. It has an optional value argument which determines the order of the component; the default value is Ordered.LOWEST_PRECEDENCE. This marks that the component has the lowest priority among all other ordered components.

In SecurityConfiguration, we will override configure method which takes HttpSecurity. Then we will override another configure method which takes AuthenticationManagerBuilder as input, we will be doing in memory authentication. We will create a user with role as USER.

Now we will create a rest endpoint with name UserController, which allows the client apps to find out more about the users that authenticate with the server.

Build Client App

GIT URL: OAuth 2.0 Client App

Let's create a Spring starter project with name 'spring-security-client'.
  • Type: gradle
  • Group: com.khs.oauthclient
  • Artifact: spring-security-client
  • Dependencies: Web(spring-boot-starter-web), Thymeleaf(spring-boot-starter-thymeleaf), Thymeleaf extras(thymeleaf-extras-springsecurity), OAuth2 Client(spring-boot-starter-oauth2-client).
Rename the src/main/resources/application.properties to application.yml and update it

Create a WebController class, this controller will map incoming requests to your Thymeleaf template files (which we will be creating).


Create a new package com.khs.oauthclient.config and create a new class with name SecurityConfiguration in it. This class defines the Spring Security configuration for your application: allowing all requests on the home path and requiring authentication for all other routes. It also sets up the Spring Boot OAuth login flow.

Now we need toadd are the two Thymeleaf template files inside src/main/resources/templates directory. API's in WebController are simply returning strings for the routes. When the Thymeleaf dependencies are included the build, Spring Boot automatically assumes we are returning the name of the template file from the controllers, and so the app will look in src/main/resources/templates for a file name with the returned string plus .html.
index.html

securedPage.html

Test the Resource Server

Run both 'spring-security-auth-server' and 'spring-security-client'. Go to the browser and open http://localhost:8082/

Click on the login link, enter username as 'admin' and password as 'admin' (we have configured the same in application.properties file of 'spring-security-auth-server'). After the authentication it will show 'Secured Page' with the username printed (in our case it will be admin).




-K Himaanshu Shuklaa..

No comments:

Post a Comment