xetra11
xetra11

Reputation: 8837

CORS and Spring MVC Services - How to setup cross origins hosts?

Preface

Consider these two webapps I have running locally:

On my local development environment (working)

When I visit my Frontend Webapp I have JavaScript executed in the background. This JavaScript is firing XHR Requests to my Service Webapp. These calls are blocked by SOP (Same Origin Policy). Because my Frontend Webapp tries to call a service on another origin (which is port 2020 in this case).

To use CORS (Cross Origin Resource Sharing) I allowed my Frontend Webapp to access the Resource of my Service Webapp with Spring's @CrossOrigin (Documentation) annotation.

  @CrossOrigin(Resources.Origins.FRONTEND) // http://localhost:8080
  @GetMapping(Resources.Services.APIs.History.STREAM)
  public SseEmitter subscribeToHistoryEvent() {
    // logic
  }

After I setup this I was successfully able to fire XHR Requests from my Frontend Webapp to my Service Webapp.

On my virtual machine deployment environment (not working)

I then tried to deploy my applications to my virtual machine to test things from a remote perspective.

The webapps were now reachable by these URLs

I was able to access my Frontend Webapp but it was not possible to fire XHR Requests to my Service Webapp again due SOP.

I think it is because I am now firing an XHR Request from my machine 192.50.3.100 to the Service Webapp which actually does only allow http://localhost:8080 to access its resouces.

My Conclusion

I misunderstood the way CORS should be used here I think. I should not fire XHR Request via JavaScript therefore from my BrowserClient to any cross origin service but I should rather call to my Frontend Webapp and let it do requests to another service living in another origin?

Please tell me what the right way of using CORS to step over SOP would be!

Upvotes: 0

Views: 666

Answers (1)

StanislavL
StanislavL

Reputation: 57381

When you try to access http://localhost:8080 from your front end it accesses localhost of machine where JS is executed (where browser starts in fact).

Instead JS should call real IP of backend - 192.20.1.77:2020 rather than localhost:2020.

Upvotes: 1

Related Questions