Spring Security Tutorial 4 – Create Your Own Login Form

Spring Security Tutorial 4

In this Tutorial, would see how to add custom Login Form. So instead of using the generated form we’ll build one. You can find Tutorials 1 to 3 below

We would cover the following 4 topics;

  1. Add Login and Logout Pages
  2. Modify the AppSecurityConfig File
  3. Write the Methods for Login and Logout
  4. Add Logout Link to the Home Page

 

1. Add Login and Logout Pages

Follow the steps below to add custom login and logout pages

Step 1: Create a html page (for login) inside the templates folder. Name it login.html. The content of the body section be as shown below. Note the action of the form. Also note the th: prefix as we are using thymeleaf

Finally, see that the span displays message for invalid credentials

<h1>Login</h1>
<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION] != null and session[SPRING_SECURITY_LAST_EXCEPTION].message != null}" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>

<form th:action="@{/login}" method="post">
<table>
<tr>
	<td>Username:</td>
	<td><input type="text" name="username" value=""></td>
</tr>
<tr>
	<td>Password:</td>
	<td><input type="text" name="password"></td>
</tr>
<tr>
	<td><input name="submit" type="submit" value="submit"> </td>
</tr>
</table>
</form>

 

Step 2: Create another html page. Name it logout.html. The content of the body section is as shown below

<h1>Logout Home</h1>
<a th:href ="@{/home}">Home</a>

 

2. Modify the AppSecurityConfig File

Step 3: Open the AppSecurityConfig file and override the configure(HttpSecurity http) method

Step 4: Write the following code inside the method

@Override
protected void configure(HttpSecurity http) throws Exception {
	http
	.csrf().disable()
	.authorizeRequests().antMatchers("/login").permitAll()
	.anyRequest().authenticated()
	.and()
	.formLogin()
	.loginPage("/login").permitAll()
	.and()
	.logout().invalidateHttpSession(true)
	.clearAuthentication(true)
	.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
	.logoutSuccessUrl("/logout-success").permitAll();
}

 

Before I move on to the next step, let me explain to you the meaning of some of the codes in the above snippet

.csrf().disable(): this line disables cross-site-request-forgery security

.authorizeRequests().andMatchers(“/login”).permitAll(): indicates that request must the authorized except for “/login”

.formLogin(): this is the main part. It allows you to use a custom login form

.logout().invalidateHttpSession(true): destroy the session once the user logs out

.clearAuthentication(true): this plays similar role  as the preceding line above

.logoutRequestMatcher(new AntPathRequestMatcher(“/logout”)): specify path to the logout page

.logoutSuccessUrl(“/logout-success”).permitAll(): the url to call on logout

 

3. Write Methods for Login and Logout

Now, we are going to write methods to call when login and logout requests are made.

Step 1: Open the HomeController File

Step 2: Write the method below to handle login requests

@RequestMapping("/login")
public String loginPage() {
	return "login";
}

 

Step 3: Write the following method to handle logout request

@RequestMapping("/logout-success")	
public String logoutPage() {
	return "logout";
}

 

At this point, we have completed the neccessary configuration.

Step 4: Fire up the application. Visit http://localhost/home.  You will be prompted for a username and password. Enter the username and password and click on login. If it works, then congratulations! Otherwise, watch the video

 

4. Add Logout Link to the Home page

Open the home page (index.html) and add the code to make a logout request. Add the code below the ‘Subscribe <br>. This is shown below

<br>
<a th:href ="@{/logout}">Logout</a>

 

Now, relaunch the application. Try to login. Then try to logout and make sure everything works.

In the next lesson, we would try to implement the OAuth 2.0 using existing user accounts.

3 Comments on “Spring Security Tutorial 4 – Create Your Own Login Form”

Leave a Reply

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