【问题标题】:Global method security in Spring BootSpring Boot 中的全局方法安全性
【发布时间】:2014-03-07 15:19:37
【问题描述】:

我在尝试在 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 文件来设置它的方法。 有什么想法吗?

更新:

正如 cmets 中所指出的,方法应该是公开的才能被代理。

【问题讨论】:

  • 控制器方法是否需要公开才能被@Secured代理?
  • 就是这样!你拯救了我的一天。

标签: spring spring-mvc spring-security spring-boot


【解决方案1】:

控制器方法需要公开才能被@Secured 代理。这样做应该可以解决它。

【讨论】:

  • 以及如何将未经授权的页面重定向到“拒绝访问”页面?
  • 我不认为这与这个问题有关吗?
【解决方案2】:

在 XML 中,您必须在 servlet-context.xml 文件中定义第二个 global-method-security。这是因为有两个上下文,根上下文和 Web 上下文,并且需要在每个上下文中单独配置安全性。

在Java config中,尝试创建一个单独的web配置类,并用@EnableWebMvc标记:

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

【讨论】:

  • Spring Boot @EnableAutoConfiguration 已经做到了,所以我认为这不是问题。
  • 这个类在这里做了什么 proxyTargetClass = true ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 2019-09-13
  • 1970-01-01
  • 2021-07-14
  • 2016-05-14
  • 2017-07-02
  • 1970-01-01
相关资源
最近更新 更多