繁体   English   中英

Spring:如何以编程方式检查给定端点是否安全

[英]Spring: How to check programmatically if given endpoint is secured

我正在将 Spring Boot 和 Oauth2 用于 Spring Security,我想检查给定的 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()注册.permitAll() ,我如何以编程方式检查? 即使我使用的是基本或摘要授权,是否有简单的方法可以做到这一点?

您可以编写一个测试来断言请求给定路径的结果。 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"));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM