2014-02-10 61 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

相关问题