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" />