Spring Security Tutorial 1 – An Introduction (Step by Step)

I would teach you how to work with Spring Security.

We would follow a step by step pattern. The steps are as follows:

  1. Create an unsecured web application
  2. Add default Spring Authentication
  3. Test the application
  4. Add login details in the application.propeties file and test the application
  5. Extend the WebsecurityConfigurer
  6. Create a UserDetails object
  7. Test the application
  8. Next Steps (Storing user details in a database)

Let’s now see the details of what happens in these steps.

 

1. Create an Unsecured Web Application

I’m sure by now you know how to create a starter application. So create one. Remember to add the following dependencies:

  • Thymeleaf
  • spring-web-starter

After creating the application and adding the dependencies, the follow the steps:

Step 1: In the templates folder, create a html page. Call it index.html.

Step 2: Write some welcome message in this html file

Note: the templates folder is found inside the src/main/resources folder

Step 3: Create  class and call it HomeController.

Step 4: Annotate this class with the @Controller annotation

Step 5: Write a method inside this class to return the index.html page.

Step 6: Annotate this method with the @RequestMapping of “/home”

The HomeController class would now look like this.

 

@Controller
public class HomeController {
	
	@RequestMapping("/home")
	public String goHome() {
		return "index";
	}
	
}

 

The index.html page would look like as shown below:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring Security</title>
</head>
<body>
<br>
<h2 align="center"> Welcome to Spring Security</h2>
</body>
</html>

 

Now you can launch the application. Visit http://localhost/home. You will notice that there is no security. You can easily access that page.

Let’ s now add authentication.

 

2. Add Default Spring Authentication

You can add a default authentication. If you do this, then you will have a simple login form created for you. Also you with have a username and password.

So simply add on dependency. That dependency is spring-boot-starter-security

Go to Maven repository to get this dependency. Or you can just copy it from below.

Put it in the depencencies section of your pom.xml file.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.1.6.RELEASE</version>
</dependency>

 

Now, save everything. Then launch the the application. Visit the same home page http://localhost/home.

You will now notice that you are presented with a login page:

Login Page for Spring Authentication

Now, the default username is “user”. You  can find the password in the console output as shown below:

Generated Password

 

Next, we would add login information to the application propeties file

 

4. Add login details in the application.propeties

Open the application.properties file

Add the following login details. You can also use username and password of your choice.

 

spring.security.user.username="kindson"
spring.security.user.password="root"

 

Now, launch the application. Notice that there is no password generated.

Go ahead to test the application using these details.

Note: for some reason, this did not work when I tested it. So if it does not work for you, just move on to the next part.

 

5. Extend the WebSecurityConfigurerAdapter

We are going to create a class that extends WebSecurityConfigurerAdapter. According to the Spring documentation, the WebSecurityConfigurerAdapter works with the @WebSecurity annotation to provide web-based security. It does the following:

  • requires that the user be authenticated before accessing resources
  • creates a user with default credentials of ‘user’/’password’ and role of ‘ROLE_USER’
  • enables basic HTTP and form authentication
  • redirects user to login page

Follows the steps below to extend WebSecurityCofigurer:

Step 1: Create a class and give it a name AppSecurityConfig (you can use another name if you want)

Step 2: Make this class extend WebSecurityConfigurerAdapter (just add extends WebSecurityConfigurer to the class)

Step 3: Annotate the class with the following annotations:

  • @EnableWebSecurity
  • @Configuration

Step 4: Write a method that overrides the userDetailsService() method (to do this, right-click and choose Source >> Override/Implement Methods. Choose UserDetailsService and click ok)

Step 5: Annotate this method with the @Bean annotation. (also make sure the @Override annotation is added)

Step 6: Inside this method,  create an empty new ArrayList of UserDetails. I call it users.

Step 7: Create a few UserDetails objects

Step 8: Add the objects to the List

Step 9: Return a new InMemoryUserDetailsManager() giving it the users list.

The final class would be as shown below:

 

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	@Bean
	protected UserDetailsService userDetailsService() {
		 
		List<UserDetails> users = new ArrayList<>();
		users.add(User.withDefaultPasswordEncoder().username("kindson").password("root").roles("USER").build());
		users.add(User.withDefaultPasswordEncoder().username("jadon").password("pass").roles("USER").build());
		users.add(User.withDefaultPasswordEncoder().username("solace").password("pass").roles("USER").build());
		
		return new InMemoryUserDetailsManager(users);
		
	}

 

Here, we created three users: kindson, jadon and solace.

Step 10: Launch the application. Test it using the three users we have created.

If everything works fine, then you have done well. Congrats! Also feel free to follow the video lesson if it is easier for you to follow

 

8. Next Steps

In real applications, however, you probably will not create users this way. Normally, user details would be stored in a database. So the question is, how do we achieve this?

The would be explained in the next tutorial – Getting Username and Password from MySQL Database.

Remember to watch the video lessons below:

 

The complete video lessons are given below

Also subscribe for updates.

Admin bar avatar

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

6 thoughts on “Spring Security Tutorial 1 – An Introduction (Step by Step)

  1. Pingback: Spring Security Tutorial – Using BCrypt Password Encoder – Part 3 | Nikkies Tutorials
  2. Wow, this paragraph is nice, my younger sister is analyzing such things, therefore I am going to let know
    her.

  3. Hi Kindson,u
    When I follow your code snippet, I got the below error in UserDetailsService. I have given the error below.

    The method withDefaultPasswordEncoder() is undefined for the type UserThe method
    withDefaultPasswordEncoder() is undefined for the type UserThe method withDefaultPasswordEncoder() is undefined for the type UserThe method withDefaultPasswordEncoder() is undefined for the type User

Leave a Reply

Your email address will not be published. Required fields are marked *