Reputation: 8837
Consider these two webapps I have running locally:
localhost:8080
localhost:2020
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.
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
192.50.3.100
192.20.1.77:8080
192.20.1.77:2020
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.
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
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