简体   繁体   中英

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. I have both public and private areas and i used Spring Security for authentication (for the private area).

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.

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?

@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. So it is possible to mimic to any client if you have all the necessary tokens. Also, CORS is slightly for different purpose:

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. 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.

You can find additional info here: 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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