According with the official example (Secure Web Content), I have to use a form and a button with the aim to perform a logout with Spring Security. Is there a way to use a li
Thats the right answer.
<form th:action="@{/logout}" method="post">
<input type="submit">POST LOGOUT</input>
</form>
You have to use a form for log out. If you really want a link, you can use JavaScript to have the link perform a POST on a hidden form.
<a href="javascript: document.logoutForm.submit()" role="menuitem"> Logout</a>
<form name="logoutForm" th:action="@{/logout}" method="post" th:hidden="true">
<input hidden type="submit" value="Sign Out"/>
</form>
The solution (deprecated!) is:
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
It is recommended to use POST instead of a GET request for security, as mentioned above.
"In order to help protect against CSRF attacks, by default, Spring Security Xml Configuration log out requires:
Hello Spring Security Xml Config
<form th:action="@{/logout}" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
<input type="submit">LOGOUT</input>
</form>
I have successfully used <a th:href="@{/logout}">Logout</a>
The relevant Spring Security config I used was
http
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login");
With respect to the context of this question I think vdenotaris wants a link not a submit button for the log out functionality. well I think what you can do is create a hyperlink like this :
<a href="#" th:href="@{/logout}">Log Out</a>
and now create a controller with below mapping :
@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}