Pregunta

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 link with Thymeleaf instead of a button?

¿Fue útil?

Solución

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> 

Otros consejos

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";
}

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.

Thats the right answer.

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

"In order to help protect against CSRF attacks, by default, Spring Security Xml Configuration log out requires:

  • the HTTP method must be a POST
  • the CSRF token must be added to the request. You can access it on the ServletRequest using the attribute _csrf as illustrated above."

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>

Try adding the following snippet of code in your file:

  <!--In case of csrf enabled post logout is working -->

  <form th:action="@{/logout}" method="post">
    <input type="submit" value="POST LOGOUT"></input>
  </form>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top