Spring Security to secure a web application

The Spring Boot framework contains a module called Spring Security. It helps to secure web application resources from unauthorized access with minimal coding.

It provides authentication, authorization and many other features for simple to enterprise level applications. If authentication is successful, the resource is accessed. Otherwise, the user is restricted.

The Spring Security is an open platform. It is quite simple for a developer to write his or her own authentication mechanism. Many developers using Spring Security need to integrate it with their own systems that don’t follow any particular security standards. In this case Spring Security is flexible to work in integration.

Prerequisites

  • An IDE for e.g. IntelliJ IDEA
  • JDK 1.8 or later
  • A Spring MVC application with login form having a list of authorized users.
  • A build system of either Gradle 4 or later or Maven 3.2 or later

Step 1:
Update the build.gradle or POM.xml

For the Gradle build system, you have to add a dependency for the Spring Security to work. The code you have to add in below “dependencies”

dependencies {
compile("org.springframework.boot:spring-boot-starter-security")
}

If your project is using the Maven build system, then add the following line of code in <dependencies> section in POM.xml

<dependencies>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-security</artifactId>
   </dependency>
</dependencies>

Step 2:
Set security configuration in the application

In this step, you will create a configuration class. It will be extended by WebSecurityConfigurerAdapter and you will override it’s configure() and userDetailsService() methods. The configure() method will contain code for two types of application paths, one for which the security is required, and other for which security is not required.

The userDetailsService() method is used to store an in-memory user. A user can authorize using the credentials coded in this method.

The below is the complete configuration file named WebSecurityConfiguration.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http
               .authorizeRequests()
               .antMatchers("/", "/main").permitAll()
               .anyRequest().authenticated()
               .and()
               .formLogin()
               .loginPage("/userLogin")
               .permitAll()
               .and()
               .logout()
               .permitAll();
   }

   @Bean
   @Override
   public UserDetailsService userDetailsService() {
       UserDetails user =
               User.withDefaultPasswordEncoder()
                       .username("user")
                       .password("password")
                       .roles("USER")
                       .build();
       return new InMemoryUserDetailsManager(user);
   }
}

The “/” and “/main” paths are configured to not require any authentication. All other paths must be authenticated.

As for the userDetailsService() method, it sets up an in-memory user store with a single user. That user is given a username of “user”, a password of “password”, and a role of “USER”.

Step 4:
Create a login form to access your web application

After the security is applied to the application’s path, it’s time to see them working. You will create a login page which will take username and password and will send it to the “main” URL which is the entry page to the application. If the credentials are correct, the user will be able to access any URL of the application. Below is a simple login page build in the HTML. The file is main.html.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
     xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
   <title> Main Page </title>
</head>
<body>
<h1>Welcome</h1>
<form th:action="@{/main}" method="post">
   <div><label> User Name : <input type="text" name="username"/> </label></div>
   <div><label> Password: <input type="password" name="password"/> </label></div>
   <div><input type="submit" value="Sign In"/></div>
</form>
<div th:if="${param.error}">
   Username or password is incorrect, you are not authorized to login. Thanks.
</div>
</body>
</html>

The form in above file will submit username and password to the URL main. When submitted, the Spring Security will come into action and will perform the appropriate action based on credentials.

You will add this HTML view to MVC controller class to make it associated with the feature.

public void addViewControllers(ViewControllerRegistry registry) {
       registry.addViewController("/main").setViewName("home");
}

Step 4:
Test the feature

Accessing the main URL, a user will get the following page.

After successful login, the user will be able to access all the resources (URLs) of the application.

Conclusion

To enable Spring Security in your Spring Boot application, you will need to add it’s dependency in the project’s POM or build.gradle file according to the build system used. Then you have to create a configuration file. It will contain URLs which require authentication and which do not. Then you need a login page to submit the credentials to Spring Security to let it decide whether to allow the user to log in or not. You will need to add the login page to the controller of the application.

Check out these top 3 Java hosting services:

HostArmada
$1.79 /mo
Starting price
Visit HostArmada
Rating based on expert review
  • User Friendly
    4.5
  • Support
    4.5
  • Features
    4.5
  • Reliability
    4.5
  • Pricing
    4.0
IONOS
$1.00 /mo
Starting price
Visit IONOS
Rating based on expert review
  • User Friendly
    4.5
  • Support
    4.0
  • Features
    4.5
  • Reliability
    4.5
  • Pricing
    4.3
Ultahost
$2.90 /mo
Starting price
Visit Ultahost
Rating based on expert review
  • User Friendly
    4.3
  • Support
    4.8
  • Features
    4.5
  • Reliability
    4.0
  • Pricing
    4.8
  • Want to get top recommendations about best hosting? Just click this link!

How to Create a Dynamic Web App with Django

Overview As a “batteries included” framework, Django
3 min read
Mark Armistead
Mark Armistead
Author

How to Install Apache Cassandra on an Ubuntu 18.04 VPS or Dedicated Server

This tutorial will help you install and configure Apache Cassandra (an opensourc
3 min read
Max Ostryzhko
Max Ostryzhko
Senior Web Developer, HostAdvice CTO

How To Install Java On CentOS 7?

This tutorial will help you install Java and manage its different versions on Ce
5 min read
David Malcom
David Malcom
Author

How to Install and Configure Apache Tomcat on an Ubuntu 18.04 VPS or Dedicated Server

Apache Tomcat is an open source java servlet container and implements Java Servl
3 min read
Kennedy Mbuvi
Kennedy Mbuvi
Author
HostAdvice.com provides professional web hosting reviews fully independent of any other entity. Our reviews are unbiased, honest, and apply the same evaluation standards to all those reviewed. While monetary compensation is received from a few of the companies listed on this site, compensation of services and products have no influence on the direction or conclusions of our reviews. Nor does the compensation influence our rankings for certain host companies. This compensation covers account purchasing costs, testing costs and royalties paid to reviewers.
Click to go to the top of the page
Go To Top