title: Spring security: how to turn off /logout for non-logged users?
body: <p>I am building a spring security app. Login and logout are working fine, but I would like to make it impossible for non-logged users to logout which is possible by default (strange...).</p>
  
  <p>I tried to add a custom Controller for /logout (checking if user is authenticated) but nothing seems to be working. Is there a way to do it in spring configuration instead? Below is my code. The controller is not working. The default spring-security /logout view is visible even if user is not authenticated.</p>
  
  <pre><code>package com.example.demo.config;
  
  import com.example.demo.security.CustomAccessDeniedHandler;
  import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  import org.springframework.security.web.access.AccessDeniedHandler;
  import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  
  @Configuration
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Bean
      public AccessDeniedHandler accessDeniedHandler() {
          return new CustomAccessDeniedHandler();
      }
  
      protected void configure(HttpSecurity http) throws Exception {
          http
                  .authorizeRequests()
                  .antMatchers("/**").permitAll() // This will be your home screen URL
                  .antMatchers("/css/**").permitAll()
                  .antMatchers("/assets/css/js/**").permitAll()
                  .anyRequest().authenticated()
                  .and()
                  .formLogin().permitAll()
                  .and()
                  .exceptionHandling()
                  .accessDeniedHandler(new CustomAccessDeniedHandler())
          ;
      }
  }
  
  -----------------
  @RequestMapping("/logout")
      public String logout() {
          if (!(SecurityContextHolder
                  .getContext()
                  .getAuthentication()
                  .getPrincipal() instanceof MyUserPrincipal)) {
  //            System.out.println("Non logged user is trying to logout");
              return "redirect:/";
          } else {
  //            System.out.println("Logged user is trying to logout");
              return "redirect:/logout";
          }
      }
  </code></pre>