Securing REST services and web applications with spring boot security starter

Security is one of the predominant aspects one must consider when developing any application or service.

Security culture can achieve more than prohibition posture.

This article will cover step by step guide to implement spring security for spring boot applications.

For instance, we will implement spring security for the following API’s:

testApiController.java

1. Add Spring boot starter dependency

build.gradle

2. Configure spring boot security:

We can configure spring security Authentication providers in multiple ways.

In this article, We will see configure it with two authentication providers:

1. An in-memory authentication provider.

In this case, we will store the username and password to be used during authentication in the properties(application.yml) file.

application.yml

We can directly use username and password in code instead of keeping in properties file but it is not a good practise as in future if it gets change then one need to make change in code which is not feasible for anyone other than developer.

SecurityConfiguration.java
  • WebSecurityConfigurerAdapter allows customization to both WebSecurity and HttpSecurity.
  • antMatcher() tells spring to only configure HttpSecurity if the path matches this pattern. That is it applies authorization to one or more paths.

Due to security reasons we should NEVER store passwords in plain text format. It must be store in encrypted format.

  • BCryptPasswordEncoder: It is an implementation of Spring’s PasswordEncoder interface that uses the BCrypt strong hashing function to encode the password.

2. A custom authentication provider.

We will implement a custom authentication provider using AuthenticationManagerBuilder.

Here configurations are store in DB.

UserDetailsServiceImpl.java: It will implement UserDetailsService which locates user based on the username.

UserDetailsServiceImpl.java

CredentialRepository.java: It will fetch the user by username from DB.

CredentialRepository.java
  • UserDetailsService: It is used as a User DAO.It is the strategy used by DaoAuthenticationProvider.
  • requests matched against "/app1/spring-security/test” require a user to be authenticated and must be associated to the ADMIN role.
  • requests matched against "/app2/spring-security/test" are fully accessible.

For any unauthorized access to the above API’s it will show the following error :

--

--

Shradha Yewale
Spring boot framework by shradha yewale

Software Development Engineer | API Development | Web Development| Java | Spring Boot | React JS