Response for preflight has invalid HTTP status code 403 + angular 2 + Java Spring boot - spring

I am making an API GET call to the server with following headers in angular 2. My angular 2 code is as follows:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `${this.publisherAccessTokenVar}`);
let options = new RequestOptions({ headers: headers });
return this.http.get( 'https://blahblah', options)
.retryWhen((error) => error.delay(this.appConfig.serviceCallRetryDelay))
.timeout(this.appConfig.serviceCallRetryTimeOut)
.map((response: Response) => response.json());
MY spring boot CORS code is as follows:
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest) req).getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Request-Method,Access-Control-Request-Headers,Content-Type, Accept, X-Requested-With, remember-me, Authorization, X-XSRF-TOKEN");
chain.doFilter(req, res);
I am getting following error:
OPTIONS http://blah-blah.com/abcd/logout 403 (Forbidden)
XMLHttpRequest cannot load http://blah-blah.com/abcd/logout. Response for preflight has invalid HTTP status code 403
How to solve this??

you have to add #CrossOrigin before your controller declaration .

Related

springboot rest api how to answer to a preflight request sent by the CORS

I'm developing a webapp angular-springboot with some other people, and to a few of those certain requests of the app are blocked by the cors with this error:
Access to XMLHttpRequest at 'https://localhost:8443/api/contratto/update' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
so I have researched what a preflight request is and I've added this method to the controller:
#RequestMapping(value = "/update",method = RequestMethod.OPTIONS)
public ResponseEntity<String> preFlightHandler(){
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Access-Control-Allow-Origin",
"https://localhost:8443");
return ResponseEntity.ok()
.headers(responseHeaders)
.body("gggg");
}
but it never even gets executed, how do I create a method mapped specifically for preflights?
didn't make a method mapped for that but I solved the error, Im' using the WebSecurityConfigurerAdapter and in the method configure(HttpSecurity http) I added the line
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
I have backend API which was accessible with GET, but couldn't be successful with POST, due to PREFLIGHT issue, which incurred CORS blockage.
Thus, in this site,
https://newbedev.com/http-request-from-angular-sent-as-options-instead-of-post#:~:text=HTTP%20request%20from%20Angular%20sent%20as%20OPTIONS%20instead,is%20allowed%20from%20a%20particular%20domain%20as%20follows%3A
I have found that, you just simply play with OPTIONS method, which your browser calls to backend for before "ACTUAL" call. this is called Preflight request.
It uses OPTIONS method instead of get/post/put. Thus, this might be of help.
If you use Node Js Server:
if (req.method == "OPTIONS")
{
res.writeHead(200, {"Content-Type": "application/json"});
res.end();
}
With PHP, I use this code:
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("HTTP/1.1 200 ");
exit;
}
These are my headers in PHP:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("HTTP/1.1 200");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With, Origin");
Note the OPTIONS method in the headers.
If you use other language, that might be easy for you using this concept.
That's it.

CORS issue for google scholars api

I am getting CORS issue while calling http://scholar.google.com/scholar?hl=en&q=java
Access to XMLHttpRequest at
'http://scholar.google.com/scholar?hl=en&q=java' from origin
'http://localhost:57013' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: Redirect is not
allowed for a preflight request.
const GOOGLE_SCHOLAR_URL =
'http://scholar.google.com/scholar?hl=en&q=java';
final dio = Dio();
final resp = await dio.get(GOOGLE_SCHOLAR_URL,
options: Options(headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods':
'GET, POST, PATCH, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token'
}));

Access-Control-Allow-Headers header not being added in response for cors non simple request?

For the non simple cors request i am adding the following headers.
def testPostJSON(){
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
render request.JSON.name
}
But you can see Access-Control-Allow-Headers is missing in the response headers. What is the reason it is missing? I am using Grails 2.2 for the server. Thanks for help!
This plugin solved the problem.
https://grails.org/plugin/cors

Access-Control-Allow-Origin error for cross platform

Hi I am trying to post some information on ajax call with cross domain. unfortunately i am getting below error.
XMLHttpRequest cannot load http://prodservices.apps.h2radio.com:8080/util-services/contributor/feedback. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://rivetnewsradio.com' is therefore not allowed access
I have searched for the above error and i have integrated below code in filter.
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
//response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with, my-cool-header");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
even I am getting same error i don't know how to resolve it. can any one give me the trick to get on.
* won't work as Access-Control-Allow-Origin When Access-Control-Allow-Credentials is set to true. So, try specifying the exact base URL, e.g. http://localhost:9000.
Instead of hardcoding the URL, you could use a property. If multiple sites could access your server, then a common practice is to get the site's base URL dynamically and checking it against a whilelist. I have it like this:
String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin",
ArrayUtils.contains(properties.getAllowedOrigins(), origin) ?
origin : properties.getDefaultApplicationUrl());
It wouldn't be considered a good practice, but if you must allow all URLs, just replace the * with request.getHeader("Origin").

Sending ajax request between https

I'm using angular to send ajax request to nodejs file, and I'm having this error,
XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost' is therefore not allowed access.
sending it from index.html to https://localhost:3000/SetUser, and direction what could go wrong and how can I allow that access of Access-Control-Allow-Origin?
-- edit:
I googled and I found this lines
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
but I still get the same error, this is the current app.post
app.post('/SetUser', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
console.log("New user added ", req.body);
});
thanks!

Resources