首页 文章

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

提问于
浏览
-1

我正在使用Spring Boot和Oauth2进行Spring Security,我想检查所有用户是否可以访问给定的API endpoints .

示例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() 注册)?即使我使用基本或摘要授权,是否有简单的方法可以这样做?

1 回答

  • 0

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

相关问题