Spring Security Java Config not generating logout

2019-01-18 05:38发布

问题:

I am using Spring 4.0.5.RELEASE and Spring Security 3.2.4.

I am trying to create a simple sample app using java config (based on the Spring samples). The app starts up and the authentication works correctly, that is, I am redirected to a login form when accessing protected url /settings/profile

However there is no /logout url generated? if I hit localhost:8080/logout I get a 404.

I've used similar code on a previous project, so maybe has something to do with versions?

Heres my Security Config

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/settings/**").hasRole("ROLE_ADMIN")
                    .and()
                .formLogin()
                    .and()
                .logout()
                    .deleteCookies("remove")
                    .invalidateHttpSession(true)
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/logout-success")
                .permitAll();
    }
}

Here is my WebAppInitializer to bootstrap the app

 public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { SecurityConfig.class , MvcConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
         return new String[] {"/"};
    }
}

and finally my MvcConfig

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = {"web"})
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

回答1:

By default POST request is required to the logout url. To perform logout on GET request you need:

http
      .logout()
          .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));

Or if you want to support PUT or other method, pass this as a parameter:

http
      .logout()
          .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "PUT"));

See the Docs: http://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/reference/htmlsingle/ (section 6.5.3. Logging Out)