In this short article, I will share with you how to implement a Logout link in a Spring Boot application, instead of a button required by Spring Security by default. The reason is that a hyperlink would be easier to blend with the user interface than a button.

Normally when using Spring Security, we need to create a form in a view page (with Thymeleaf) just for having the Logout button like this:

<form th:action="@{/logout}" method="post">
	<input type="submit" value="Logout" />
</form>

When CSRF is enabled (default), Spring Security requires the /logout request must be in HTTP POST so it can generate a CSRF token in the form to prevent Cross Site Request Forgery attacks. View the page’s source and you can see a hidden input is inserted into the form as below:

<form action="/MyApp/logout" method="post">
	<input type="hidden" name="_csrf" value="07b8ec05-fe21-4819-80b1-2ad57ae9450e"/>
	<input type="submit" value="Logout" />
</form>

You can configure Spring Security to disable CSRF in order to use a hyperlink for Logout (then the logout request can be sent using HTTP GET method). For example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			....
			.and()
			.csrf().disable()
			....
	}	
}

However, it is not recommended to have CSRF disabled at that will put your application at risks of CSRF attacks. So, how to use a Logout hyperlink while still having CSRF enabled?

I will share with you some tricks to do that. First, let’s make the logout form hidden and give it an ID:

<form th:action="@{/logout}" method="post" th:hidden="true" name="logoutForm">
	<input type="submit" value="Logout" />
</form>

Then you can create a Logout hyperlink as below:

<a href="javascript: document.logoutForm.submit()">Logout</a>

Then the user clicks the Logout link, the Javascript statement will be executed, which submits the form to the server – the logout request is sent using HTTP POST method. Brilliant, right?

If you don’t want to expose the Javascript statement when the user hovers the mouse over the Logout link, you can modify the link like this:

<a id="logoutLink" href="/">Logout</a>

Then use a little bit jQuery code to handle click event of the hyperlink as below:

$(document).ready(function() {
	$("#logoutLink").on("click", function(e) {
		e.preventDefault();
		document.logoutForm.submit();
	});
});

That’s it! Now you have a Logout link which can be blended with your own user interface.

To see the code in action, watch the following video:

 

My Spring Security Tutorials:

 

Other Spring Boot Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment