Spring boot and Oauth2
In this guide we will learn how to secure a spring boot application using Oauth2. This tutorial is for developers who have experience in developing web application using Spring framework and basic understanding of Oauth2.
Technologies Used
The technologies used in this guide are:
- Spring Boot
- Oauth2
- MongoDB
- Gradle
Dependencies
Here is the list of dependencies required:
Authorization Server
Let us configure the authorization server. Let us register rokin-client as a client. We will be using in-memory token store.
Here, allowFormAuthenticationForClients() method is used for authenticating a client using form parameters instead of basic auth.
Resource Server
Security Configuration
Here, we will be using BCryptPasswordEncoder to encrypt user’s password. The AuthenticationManagerBean is required for password grant type.
User Details Configuration
Now that we have configured the security settings, authorization server and resource server, let us dive into user configurations. We will be using MongoDB to store user details. Let us start by creating a User entity.
Now, we will create a user repository to perform database queries on users collection. We will be using Spring Data MongoDB for this purpose.
For Spring Data MongoDB to work, we need to specify the database name, host, port, username and password in the application.properties file.
In order to verify that the credentials used to login are correct, we need to create a CustomUserDetailsService class which implements org.springframework.security.core.userdetails.UserDetailsService. In this class, we will fetch user from database and map it to org.springframework.security.core.userdetails.User.
Now that all of our configurations are done, let us insert a user in database during application startup. This is important because we cannot generate an access token using password grant without a user in our database.
Token endpoints
Access and Refresh token
To get access and refresh token, first, update your request with your client id and client secret in the Authorization header.
Then, in your body set grant_type as password and provide your username and password.
Access Token from Refresh Token
Just as the when getting access token, first, update your request with your client id and client secret in the Authorization header. Then, in your body set grant_type as refresh_token and provide the refresh_token.
If you want to check out the complete project on github, please visit https://github.com/rokinmaharjan/spring-security-oauth2.
This is the end of this guide. Don’t forget to clap if you liked it. :)