Logout link with Spring and Thymeleaf

后端 未结 6 1273
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 23:23

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

相关标签:
6条回答
  • 2021-01-03 23:42

    Thats the right answer.

    <form th:action="@{/logout}" method="post">
        <input type="submit">POST LOGOUT</input>
    </form>
    
    0 讨论(0)
  • 2021-01-03 23:45

    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> 
    
    0 讨论(0)
  • 2021-01-03 23:48

    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.

    0 讨论(0)
  • 2021-01-03 23:54

    "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>
    
    0 讨论(0)
  • 2021-01-04 00:03

    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");
    
    0 讨论(0)
  • 2021-01-04 00:03

    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";
    }
    
    0 讨论(0)
提交回复
热议问题