0

I have implemented two Spring boot applications, where one spring boot application gives a rest call to another. In the second spring boot application I have implemented CORS by using annotation @CrossOrgin and specified origin as localhost:8085.

I tried to bring up the calling application on other port other than 8080 and again gave a call to this resource(with @CrossOrigin) Ideally it should accept request from only this host but it is accepting from other host as well

I want to implement this on jdk8 n spring boot version 2.7.10

Am i missing anything?

@CrossOrigin is not restricting calls from other origin which are not specified in origin list

Client Code :
package com.example.CORSExampleClient.CORSClient;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class CORSClient {

    @Autowired
    private RestTemplate restTemplate;
    
    @GetMapping("callClient")
    public void callClient() {
        String response=restTemplate.getForObject("http://localhost:9000/getOrigin",String.class);
        System.out.println("Response "+response);
        
    }
    
    
}

**Other Resource Code with CORS restriction**
package com.example.CORSExample;


import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin(origins = "http://localhost:8085")
@RestController
public class CORSController {

    @GetMapping("getOrigin")
    public String getOrigin(@RequestParam(required = false, defaultValue = "World") String name){
        return "Hello "+name;

    }
}

**Main class in CrossOrgin application**

package com.example.CORSExample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CorsExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(CorsExampleApplication.class, args);
    }

}
Darshana
  • 1
  • 2
  • 2
    Contrary to popular belief, the purpose of CORS is _not_ to restrict access. Rather, the purpose of CORS is to _relax_ some of the restrictions enforced by the Same-Origin Policy, which is only implemented by browsers anyway. – jub0bs Apr 04 '23 at 13:09
  • Does this answer your question? [CORS-enabled server not denying requests](https://stackoverflow.com/questions/45069689/cors-enabled-server-not-denying-requests) – jub0bs Apr 04 '23 at 20:17

0 Answers0