2014-10-01 129 views
0

我是Spring Security的新手,所以我可能會錯過某些東西。我有一個Spring應用程序,該應用程序使用我希望使用Spring Security來保護的WebApplication來啓動一個Jetty。該webapp正在運行並可以訪問,但不受限制。我嘗試了很多東西,但沒有任何工作,所以我把它分解爲一個最小的設置,但仍然沒有機會。 web應用程序由以下Java配置配置:無法讓Spring Security工作

@EnableWebMvc 
@Configuration 
@Import(SecurityConfiguration.class) 
@ComponentScan(useDefaultFilters = false, basePackages = { "myapp.web" }, includeFilters = { @ComponentScan.Filter(Controller.class) }) 
public class SpringMvcConfiguration extends WebMvcConfigurerAdapter { 
    /** 
    * Allow the default servlet to serve static files from the webapp root. 
    */ 
    @Override 
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 
     configurer.enable(); 
    } 
} 

和Spring安全以下配置:

@Configuration 
@EnableWebSecurity 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

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

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
     .authorizeRequests() 
     .anyRequest() 
     .hasAuthority("ADMIN"); 
    } 
} 

和一些控制是這樣的:

@Controller 
public class SecuredController { 

    @RequestMapping(value = "/secure", method = RequestMethod.GET) 
    @ResponseBody 
    public String secured() { 
     return "you should not see this unless you provide authentication"; 
    } 
} 

一切始於了所有的權利,日誌告訴我,控制器映射...

[2014-10-01 20:21:29,538, INFO ] [main] mvc.method.annotation.RequestMappingHandlerMapping:197 - Mapped "{[/secure],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String myapp.web.SecuredController.secured() 

...和安全到位,以及...

[2014-10-01 20:21:30,298, INFO ] [main] gframework.security.web.DefaultSecurityFilterChain:28 - Creating filter chain: [email protected]1, [org.springframework.secu[email protected]352c308, org.spring[email protected]2af616d3, [email protected]935, [email protected], org.[email protected]bc57b40, org.sp[email protected]3deb2326, org.springframework.[email protected]7889a1ac, org.springfram[email protected]7d373bcf, o[email protected]5922ae77, org[email protected]7e1a1da6, org.springfr[email protected]1051817b] 

...但/secure URL我的控制器是無條件地到達。我究竟做錯了什麼?

ps。我想避免xml配置

回答

1

爲了將Spring Security與Spring MVC集成,您必須使用@EnableWebMvcSecurity註釋,而不是類中的@EnableWebSecurity

+0

仍然沒有成功... – Ole 2014-10-01 20:47:36

0

我算了一下,我不得不在春季安全配置的初始化移動到根上下文,而不是調度員servlet上下文,並添加以下行,其中配置我的嵌入式碼頭的背景:

context.addFilter(new FilterHolder(new DelegatingFilterProxy("springSecurityFilterChain")), "/*", EnumSet.allOf(DispatcherType.class));