注销与Spring和Thymeleaf的链接

vde*_*ris 16 spring spring-mvc spring-security thymeleaf

根据官方示例(Secure Web Content),我必须使用表单和按钮,目的是使用Spring Security执行注销.有没有办法使用Thymeleaf链接而不是按钮?

小智 20

您必须使用表单进行注销.如果您真的想要一个链接,可以使用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> 
Run Code Online (Sandbox Code Playgroud)


geo*_*and 16

我已成功使用 <a th:href="@{/logout}">Logout</a>

我使用的相关Spring Security配置是

 http
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login");
Run Code Online (Sandbox Code Playgroud)

  • 查看[这个](http://docs.spring.io/spring-security/site/docs/3.2.0.RC2/apidocs/org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html# logoutUrl%28java.lang.String%29) 进行配置,然后只需将 html/thymeleaf 锚点更改为表单 (2认同)

vde*_*ris 8

解决方案(已弃用!)是:

       .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login");
Run Code Online (Sandbox Code Playgroud)

如上所述,建议使用POST而不是GET请求进行安全性.


小智 8

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

<a href="#" th:href="@{/logout}">Log Out</a>
Run Code Online (Sandbox Code Playgroud)

现在使用以下映射创建一个控制器:

@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";
}
Run Code Online (Sandbox Code Playgroud)


CES*_*SCO 6

这是正确的答案.

<form th:action="@{/logout}" method="post">
    <input type="submit">POST LOGOUT</input>
</form>
Run Code Online (Sandbox Code Playgroud)

  • 如果“有没有办法使用 Thymeleaf 的链接而不是按钮?” 问题是,如何使用按钮才是正确的答案? (2认同)