【问题标题】:Spring: How to check programmatically if given endpoint is securedSpring:如何以编程方式检查给定端点是否安全
【发布时间】:2016-01-25 15:17:21
【问题描述】:

我正在为 Spring Security 使用 Spring Boot 和 Oauth2,我想检查给定的 API 端点是否可供所有用户访问。

Oauth 配置类示例:

@Configuration
public class OAuth2ServerConfiguration {

        //(...)

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/", "/login**", "/logout**", "/denied**", "/index**")
                        .permitAll()
                    .antMatchers("/ma/**", "/maintenance/**", "/api/maintenance/**")
                        .permitAll()
//                      .hasAnyRole("ADMIN")
                    .antMatchers("/api/**")
                        .permitAll()
//                      .hasAnyRole("ADMIN", "USER")
                    .anyRequest()
                        .denyAll()
                .and()
                    .exceptionHandling()
                        .accessDeniedPage("/denied")
                .and()
                    .csrf()
                        .disable();
        }

        //(...)
}

我如何以编程方式检查,例如,enpoint /api/someMethod 是否可供所有人使用(已在 .permitAll() 注册)? 即使我使用的是基本授权或摘要授权,有没有简单的方法可以做到这一点?

【问题讨论】:

  • 即使控制器方法可以访问,也可以在Service以及webapp的DAO层进行Secured注解。对于这样的注解,如果条件不满足,则不调用该方法,你甚至都不知道。
  • 如果这有帮助,我不会使用@Secured 注释。
  • 那我不明白你的问题,因为如果你的安全限制在控制器方法之前,那么你在安全配置中没有提到的所有这些都是不安全的方法,通过推论。
  • then all of them which you have not mentioned in your security config, are insecure methods 我不这么认为,.anyRequest() 会“捕获”所有其他未配置的端点。
  • 是的,那只是因为您明确提到了denyAll。而且我仍然不知道您为什么要为自己的 web 应用提供方法列表。

标签: java spring spring-security spring-boot spring-security-oauth2


【解决方案1】:

您可以编写一个测试来断言请求给定路径的结果。 Spring Security 用户指南中有一个完整的部分:http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test。重点是使用MockMvc

或者您可以运行一个完整的堆栈集成测试,包括一个真正的 HTTP 调用。示例:

@Test
public void testHome() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    ResponseEntity<String> entity = new TestRestTemplate().exchange(
            "http://localhost:" + this.port, HttpMethod.GET,
            new HttpEntity<Void>(headers), String.class);
    assertEquals(HttpStatus.FOUND, entity.getStatusCode());
    assertTrue("Wrong location:\n" + entity.getHeaders(),
            entity.getHeaders().getLocation().toString().endsWith(port + "/login"));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 2013-05-05
    • 1970-01-01
    相关资源
    最近更新 更多