Spring Security Java Config不生成logout url

时间:2014-06-08 17:04:16

标签: java spring configuration spring-security spring-java-config

我使用Spring 4.0.5.RELEASE 和Spring Security 3.2.4

我正在尝试使用java配置创建一个简单的示例应用程序(基于Spring示例)。该应用启动并且身份验证正常运行,也就是说,在访问受保护的网址时,我被重定向到登录表单 / settings / profile

但是没有生成 / logout 网址?如果我点击localhost:8080 / logout我得到404。

我在之前的项目中使用了类似的代码,所以可能与版本有关吗?

继承我的安全配置

@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();
    }
}

这是我的WebAppInitializer来引导应用程序

 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[] {"/"};
    }
}

最后是我的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 个答案:

答案 0 :(得分:40)

默认情况下,退出网址需要POST请求。要在GET请求上执行注销,您需要:

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

或者,如果您想支持PUT或其他方法,请将其作为参数传递:

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

请参阅文档:http://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/reference/htmlsingle/(第6.5.3节“注销”)