带有Spring和Thymeleaf的注销链接

带有Spring和Thymeleaf的注销链接,spring,spring-mvc,spring-security,thymeleaf,Spring,Spring Mvc,Spring Security,Thymeleaf,根据官方示例(),我必须使用一个表单和一个按钮,以便使用SpringSecurity执行注销。 有没有办法用Thymeleaf的链接代替按钮?我已经成功地使用了 我使用的相关Spring安全配置是 http .formLogin() .loginPage("/login") .permitAll() .and() .logout() .logoutUr

根据官方示例(),我必须使用一个表单和一个按钮,以便使用SpringSecurity执行注销。
有没有办法用Thymeleaf的链接代替按钮?

我已经成功地使用了

我使用的相关Spring安全配置是

 http
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login");
解决方案(已弃用!)是:


如上所述,建议使用POST而不是GET安全请求。

这是正确的答案

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

注销后

您必须使用一个表单进行注销。如果您确实想要一个链接,可以使用JavaScript让该链接在隐藏表单上执行POST

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

关于这个问题的上下文,我认为vdenotaris想要一个链接,而不是一个用于注销功能的提交按钮。我想你能做的就是创建一个超链接如下:

<a href="#" th:href="@{/logout}">Log Out</a>
“为了帮助抵御CSRF攻击,默认情况下,Spring Security Xml配置注销需要:

  • HTTP方法必须是POST
  • 必须将CSRF令牌添加到 您可以使用属性在ServletRequest上访问它 _如上所示的csrf。”


注销

将按钮设置为链接样式。出于安全原因,它需要是一个POST而不是GET请求。您还可以将注销筛选器配置为接受get请求,但这不太安全。还可以看到,在生成get请求时,这对我不起作用。请检查配置,然后将html/thymeleaf锚更改为一个表单。这对我有效。我们需要找到一种方法来解决这个问题post@vdenotaris你能解释一下为什么它被弃用吗?我是否应该使用它?@Partho63,因为这个实现通过HTTP GET而不是POST处理注销过程,如我在回答中所述。请参阅:注意,我需要将'input'元素的'hidden'属性更改为'hidden=“true”'if“是否有方法使用与Thymeleaf的链接而不是按钮?”问题是,如何使用按钮才是正确答案?这段代码实际上正在工作。稍微解释一下它的工作原理可能会对其他观众有所帮助。
<a href="#" th:href="@{/logout}">Log Out</a>
@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";
}
<form th:action="@{/logout}" method="post">
    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" /> 
    <input type="submit">LOGOUT</input>
</form>