Spring:如何以编程方式检查给定端点是否安全
我将 Spring Boot 和 Oauth2 用于 Spring Security,我想检查给定的 API 端点是否可供所有用户访问.
I'm using Spring Boot and Oauth2 for Spring Security and I want to check if given API endpoint is accessible for all users.
示例 Oauth 配置类:
Sample Oauth configuration class:
@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()
注册)?即使我使用的是基本或摘要授权,是否也有简单的方法可以做到这一点?
How do I check programmatically if, for example, enpoint /api/someMethod
is available for all (is registered with .permitAll()
)?
Is there simple way to do so even if I'm using basic or digest authorization?
您可以编写一个测试来断言请求给定路径的结果.Spring Security 用户指南中有一个完整的部分:http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test.重点是使用 MockMvc
.
You can write a test that asserts the outcome of requesting a given path. There's a whole section in the Spring Security user guide: http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test. The focus there is on using MockMvc
.
或者您可以运行一个完整的堆栈集成测试,包括一个真正的 HTTP 调用.示例:
Or you can run a full stack integration test including a real HTTP call. Example:
@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"));
}