2014-02-10 62 views
10

我在嘗試啓用Spring Boot應用程序中的全局方法安全性時遇到了一些問題。 或多或少我有這個配置:Spring Boot中的全局方法安全性

@ComponentScan 
@Configuration 
@EnableAutoConfiguration 
@EnableConfigurationProperties 
public class Main extends SpringBootServletInitializer { 

    public static void main(String[] args) throws Exception { 
     SpringApplication app = new SpringApplication(Main.class); 
     app.setShowBanner(false); 
     ApplicationContext context = app.run(args); 
    } 

    @Override 
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
     return application.sources(Main.class); 
    } 
} 

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true) 
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Bean 
    @Override 
    public AuthenticationManager authenticationManagerBean() throws Exception { 
     return super.authenticationManagerBean(); 
    } 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     ... 
    } 

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

@Controller 
public class SampleController { 

    @RequestMapping("/api/hello") 
    @ResponseBody 
    String hello() { 
     return "Hello!"; 
    } 

    @Secured(SecurityGrant.WRITE_PROJECT) 
    @RequestMapping("/api/bye") 
    @ResponseBody 
    String bye() { 
     return "Bye!"; 
    } 
} 

的@Secure標註在服務工作正常,但不是在控制器,所以當我讀到這裏(http://docs.spring.io/spring-security/site/faq/faq.html#faq-method-security-in-web-context)我想是因爲方法的安全性僅在配置根應用程序上下文,不在servlet中。 但是,我找不到通過Java配置來設置它的方式,而不是使用web.xml文件。 任何想法?

更新:

正如在評論中指出,方法應該是公開的被代理。

+1

不要控制器方法需要公開才能代理'@ Secured'嗎? –

+0

就是這樣!你拯救了我的一天。 –

回答

11

控制器方法需要爲了公衆被代理的@Secured。只是這樣做應該解決它。

+0

以及如何將未經授權的頁面重定向到「訪問被拒絕」頁面? – Max

+0

我不認爲這與這個問題有關嗎? –

4

在XML中,您必須在servlet-context.xml文件中定義第二個global-method-security。這是因爲有兩個上下文,根上下文和Web上下文和安全性需要分別配置。

在Java配置,嘗試創建一個單獨的Web配置類,並與@EnableWebMvc標記它:

@Configuration 
@EnableWebMvc 
@EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true) 
public class WebConfig { 
    ... 
} 
+0

Spring Boot'@ EnableAutoConfiguration'已經這樣做了,所以我不認爲這是問題所在。 –

+0

這個類在這裏做了什麼proxyTargetClass = true? – Max

相關問題