Last Updated on 19 August 2020   |   Print Email
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:
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:
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:
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:
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:
Nam Ha Minh 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.