Search code examples
spring-bootspring-mvcthymeleaf

Create a Logout Link in Html Page


I have working login and logout forms with using Spring Security Basic Authentication and thymeleaf.

my problem is my logout link is display as a button. but I want to include it in a <a href=""> tag. but when I include my logout link in the <a href=""> tag it isn't working. here is my code.

Logout Controller - Spring Boot

@RequestMapping(value = {"/logout"}, method = RequestMethod.POST)
public String logoutDo(HttpServletRequest request,HttpServletResponse response){
HttpSession session= request.getSession(false);
    SecurityContextHolder.clearContext();
         session= request.getSession(false);
        if(session != null) {
            session.invalidate();
        }
        for(Cookie cookie : request.getCookies()) {
            cookie.setMaxAge(0);
        }

    return "redirect:/login?logout";
}

Logout form - Front End

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

Security Configurations

@Override
protected void configure(HttpSecurity http) throws Exception {


    http
    .requestMatchers()
    .antMatchers("/login", "/",  "/customer/**", "/registration", "/admin/**")
    .and()
    .authorizeRequests()
    .antMatchers("/admin/**").hasAuthority("ADMIN").antMatchers("/customer/**").hasAuthority("CUSTOMER")
    .antMatchers("/login", "/registration", "/").permitAll()
    .anyRequest().authenticated()
    .and()
    .httpBasic().and().csrf().disable()

    .formLogin()  //login configuration
            .loginPage("/login")
            .loginProcessingUrl("/login")
            .usernameParameter("email")
            .passwordParameter("password")
            .defaultSuccessUrl("/customer/home")    
    .and().logout()    //logout configuration
    .logoutUrl("/logout") 
    .logoutSuccessUrl("/login")
    .and().exceptionHandling() //exception handling configuration
    .accessDeniedPage("/error");

    }

Solution

  • A workaround is to submit a 'hidden' form:

    <a href="javascript: document.logoutForm.submit()" > Logout Link </a>
    
    <form name="logoutForm" th:action="@{/logout}" method="post" th:hidden="true">
          <input hidden type="submit" value="Logout"/>
    </form>