0

I have two projects A and B. Both run on different ports A(8080) B(8091). I had enabled cors origin(http://localhost:8090) in project A for endpoint "greeting". Then trying to call "greeting" endpoint from project B using resttemplate. Since cross origin in project A and the calling Project B are from different ports, I am expecting a cors related error.

But I am getting a proper response instead of an error.

I tried in chrome and postman but same result

//Project A
@RestController
public class GreetingController {
    @GetMapping("/greeting")
    @CrossOrigin(origins = "https://localhost:8090")
    public String greeting() {
        return "greetingsss";
    }
}

//Project B
@RestController
public class GreetingController {
    @GetMapping("/greeting1")
    public String greeting() {
        final String uri = "http://localhost:8080/greeting";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(uri, String.class);
        return result;
    }
}

Expected Result: failed to load, no access control allow origin

Actual Result: greetingsss

Ishaan Javali
  • 1,711
  • 3
  • 13
  • 23
  • what does your web configuration look like? – Coder Jul 29 '19 at 15:19
  • 2
    CORS is used to tell **browsers** that they may **allow AJAX requests made from code coming from another origin**. It's not used to **forbid** requests, and has nothing to do with requests coming from a Java application. If you only want to process some requests and not others, then use a filter and check the presence of a valid API key, for example. – JB Nizet Jul 29 '19 at 18:24

1 Answers1

1

CORS is a web thing imposed by user agents(browsers). Hence, service to service communication won't be affected by that. If you want to achieve that for service to service communication, use spring security where you can intercept URLs by matching certain patterns and check a variety of stuff including origin IP/domain (hasIpAddress). Here, you may deny access or allow access using various rules.

Alternatively, you may write a security filter to disallow/allow certain IP/domains.

fiveelements
  • 3,649
  • 1
  • 17
  • 16