Custom login page using Bootstrap and Thymeleaf in Spring Security

Normally, we won’t use Spring Security’s default login page for applications deployed to production, you can guess why, right? This default login page for us to learn mainly. So to replace this default login page, how do we do? In this tutorial, I will guide you to do this.

First, I will create a new Spring Boot with Spring Security, Spring Web and Thymeleaf dependencies.

The result is as follows:

Custom login page using Bootstrap and Thymeleaf in Spring Security

Running this example, you will see Spring Security’s default login page as follows:

Custom login page using Bootstrap and Thymeleaf in Spring Security

Now, I will use Bootstrap to write a custom login page.

I will use WebJars to manage the Bootstrap library:

For simplicity, my custom login page has the same components as the default login page of Spring Security, except that I replace the word “Please sign in” with the words “Welcome to Huong Dan Java, please login in” ” and the “Sign in” button is now “Login”.

The code for the login.html page is located in my src/main/resources/templates folder with Bootstrap as follows:

In addition, I also expose another page, simply to display the home page after login:

You can read more Using Thymeleaf in Spring Boot to understand why I put the login.html file in the src/main/resources/templates folder!

Now I will create a new controller to expose these pages:

After exposing the custom login page, it’s time to configure Spring Security to use this custom page.

You need to override the configure(HttpSecurity http) method:

We will configure all requests to be authenticated and use our custom login page as follows:

As you can see, from the HttpSecurity object, we will call the formLogin() method to get the FormLoginConfigurer object to configure the Spring Security login page. From this FormLoginConfigurer object, we will use the loginPage() method with the login page name as the parameter to override the default Spring Security login page.

I also configure configure(WebSecurity web) to ignore security for WebJars related links, here is the link to Bootstrap CSS.

OK, at this point, you can run the application again to check the results.

Your login page should now look like this:

Custom login page using Bootstrap and Thymeleaf in Spring Security

Login with username as user and generated password, you will see the following result:

Custom login page using Bootstrap and Thymeleaf in Spring Security

2 thoughts on “Custom login page using Bootstrap and Thymeleaf in Spring Security

  1. Hi!
    Could you explain “Login with username as user and generated password”?
    Do I need to use “username” as login?
    And what does it mean “generated password”? Where should I write my password in code?
    Thank you in advance!

Add Comment