I have this code that adds Cors Mappings to my java spring application.
It works well to allow requests comming from http://localhost:4200
.
But it is not working to allow requests from the second origin (test server).
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") //all paths
.allowedMethods("*") //all methods/endpoints
.allowedOrigins("http://localhost:4200", //dev
"http://serverip:8080"); //test server
}
I'm guessing "http://serverip:8080"
in that code is not quite right.
So I wanted to identify the exact origin where the call is comming.
Then I can add that origin "as is" in the allowedOrigins list.
How can I do that?
I tried this but it's returning null.
@RequestMapping(value = "/httprequestorigin", method = RequestMethod.GET)
public String getHttpRequestOrigin() throws UnknownHostException {
String origin = "";
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
origin = request.getHeader("HttpHeaders.ORIGIN");
}
return origin;
}
Also tried like this and it also returns null.
origin = request.getHeader("Origin");
And when I read the http headers in Chrome Dev Tools I don't see "Origin" in there.
Understand this code is not working because the origin header is not available.
So how to identify the origin of the Http request in that case?
As pointed out in the comments (creds also to jub0bs:
The backend and the frontend are served by the same endpoint (serverip:8080
). Webbrowsers will only send the origin, if backend and frontend are different hosts.
Read more about CORS at mozilla. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS