[英]How to block access to my API from Postman/Other API's/etc.. (Spring Boot)
I'm developping a Rest Api with Spring Boot and Spring Security.我正在使用 Spring 引导和 Z38008DD81C2F4D798Z5ECF6 I have both public and private areas and i used Spring Security for authentication (for the private area).
我有公共和私人区域,我使用 Spring Security 进行身份验证(用于私人区域)。
The problem is that i configured CORS and it blocks requests if i call public endpoints from unauthorized url's but and i was surprised that if i call it from Postman or another Spring Boot App using RestTemplate, the CORS don't block the request and return the result. The problem is that i configured CORS and it blocks requests if i call public endpoints from unauthorized url's but and i was surprised that if i call it from Postman or another Spring Boot App using RestTemplate, the CORS don't block the request and return the结果。
I read on Internet that the CORS is only blocking calls from browsers.. So how can i protect the public part of my API from calling it from Postman or other API's?我在 Internet 上读到 CORS 仅阻止来自浏览器的调用。那么如何保护我的 API 的公共部分不从 Postman 或其他 API 调用它?
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200","http://localhost:4201"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
I am afraid there is no solution for that.恐怕没有解决办法。 In Postman, you can add any headers you want.
在 Postman 中,您可以添加所需的任何标题。 So it is possible to mimic to any client if you have all the necessary tokens.
因此,如果您拥有所有必要的令牌,则可以模仿任何客户。 Also, CORS is slightly for different purpose:
此外,CORS 的用途略有不同:
The use-case for CORS is simple. CORS 的用例很简单。 Imagine the site alice.com has some data that the site bob.com wants to access.
想象一下站点 alice.com 有一些站点 bob.com 想要访问的数据。 This type of request traditionally wouldn't be allowed under the browser's same origin policy.
在浏览器的同源策略下,这种类型的请求传统上是不允许的。 However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data.
但是,通过支持 CORS 请求,alice.com 可以添加一些特殊的响应头,允许 bob.com 访问数据。
You can find additional info here: https://medium.com/@baphemot/understanding-cors-18ad6b478e2b您可以在此处找到更多信息: https://medium.com/@baphemot/understanding-cors-18ad6b478e2b
private Map<String, String> getRequestHeadersInMap(HttpServletRequest request) {
Map<String, String> result = new HashMap<>();
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
result.put(key, value);
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.