springboot for backend reactjs frontend - reactjs

i use springboot and reactjs everthing was working before adding security to backend, now as go to web page to retrieve my data, i do not see any data there. I go to console it says the username not defined:do not know what does it mean.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/users/undefined/todos. (Reason: CORS request did not succeed)
UPDATE: I tried to both code but did not help.
does this mean anything serious:
"Uncaught (in promise) Error: Network Error
at createError" (createError.js:16)
Access to XMLHttpRequest at 'http://localhost:8080/users/undefined/todos' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:177 GET http://localhost:8080/users/undefined/todos net::ERR_FAILED
dispatchXhrRequest # xhr.js:177
xhrAdapter # xhr.js:13
todos:1 Access to XMLHttpRequest at 'http://localhost:8080/users/undefined/todos' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:177 GET http://localhost:8080/users/undefined/todos net::ERR_FAILED
dispatchXhrRequest # xhr.js:177
xhrAdapter # xhr.js:13
dispatchRequest # dispatchRequest.js:52
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)

Add #CrossOrigin(origins = "http://localhost:3000") (if you run your client at 3000), or use this bean (in SecurityConfig):
#Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setExposedHeaders(Arrays.asList("x-auth-token", "xsrf-token"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

Related

How to fix: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header [duplicate]

This question already has answers here:
How to CORS-enable Apache web server (including preflight and custom headers)?
(1 answer)
401 error - JWT Token not found using fetch
(1 answer)
Closed 3 years ago.
I am trying to build a simple API with a php backend and a React JS frontend. I am using two separate docker containers for this (api.dev.de and react.dev.de, as it is a requirement. I am using a slightly adapted version of the nginx proxy. However, when I send the request per React fetch() to the server, I get the error:
Access to fetch at 'https: //api.dev.de/index.php?read=users' from
origin 'https: //react.dev.de' 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. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
Below you can see my request that I am trying to make and the .htaccess file.
I already looked up some solutions that worked for others, including this
one that I also wrote into my Dockerfile (and first enabling the extension for this image in my docker-compose.yml).
Furthermore I dug through
this
answer and navigated through those links to other articles to build up some knowledge, but still no success...
Here are my code snippets.
Persons.js:
...
fetch('https://api.dev.de/index.php?read=users', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa("<secretName>:<secretPass>"),
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
...
.htaccess:
Authtype Basic
AuthName "Protected section. Only for developers."
AuthUserFile /var/www/html/App/.htpasswd
Require valid-user
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials "true"
The config in the Dockerfile:
FROM thecodingmachine/php:7.3-v2-apache
...
RUN a2enmod headers
...
When executing the function, I get those console logs:
Access to fetch at 'https:// api.dev.de/index.php?read=users' from
origin 'https:// react.dev.de' 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. If an opaque response serves your needs, set the
request's mode to 'no-cors' to fetch the resource with CORS
disabled.
VM2133:1 POST https://api.dev.de/index.php?read=users
net::ERR_FAILED
However, when I delete all authentication config in the .htaccess file as well deleting the Authorization and Content-Type section from the Persons.js file, I get a valid response. But I can't just exclude my authorization from the page.
When I build the React App and paste it in the same docker container as the API and then call it, everything is working fine. So I assume it is the config of the docker container (correct me if I am wrong).
Update:
Since yesterday I tried out different things and came up with one last problem.
My fetch() function now looks like the following:
fetch('https://api.dev.de/index.php?read=users&pass=<password>', {
method: 'GET',
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
},
})
I also changed my .htaccess file:
# Enabled in the Dockerfile but still checking if it is enabled.
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Content-Type "*"
Header set Access-Control-Accept "*"
# This should enable the authentication header
Header set Access-Control-Allow-Credentials "true"
</IfModule>
Now the request works, but when I change the fetch() function to send an authorization header ('Authorization': 'Basic: ' + btoa('<username>:<password>')) and the .htaccess to this:
Authtype Basic
AuthName "Protected section. Only for developers."
AuthUserFile /var/www/html/App/.htpasswd
Require valid-user
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Content-Type "*"
Header set Access-Control-Accept "*"
# This should enable the authentication header
Header set Access-Control-Allow-Credentials "true"
</IfModule>
I still get the error:
Access to fetch at 'https://api.dev.de/index.php?read=users&pass=crud_restAPI_call' from origin 'https://react.dev.de' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Is this because the order of my .htaccess or do I need to modify something else?
Update 2:
As of my research, I found this answer to a similar issue: "The preflight request (OPTIONS), which is where i encounter the 401 unauthorized. I think this is because I've read that OPTIONS strips out some headers, including the Authentication header, so without that, it can't authenticate".
Source: https://github.com/axios/axios/issues/2076
Checking the developer.mozilla.org guide (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Sending_a_request_with_credentials_included) I wanted to send the credentials always (to get the preflight request to succeed).
However, this does not work...
Has somebody an idea why it doesn't?
Updated fetch() function:
fetch('https://api.dev.de/index.php?read=users&pass=<password>', {
method: 'POST',
credentials: 'include',
headers: {
'Authorization': 'Basic: ' + btoa('<secretName>:<secretPass>'),
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
},
})
I still get the same error:
Access to fetch at 'https://api.dev.de/index.php?read=users&pass=crud_restAPI_call' from origin 'https://react.dev.de' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The preflight requests are not Docker related issue, they are browser-related policy. You're using HTTP headers that trigger the preflight mechanism, "Authorization" header in your case, and doing a cross-origin calls from the domain of your website to the api.dev.de domain.
You can read this article about avoiding preflights.
I would go with just adding an endpoint to your api server that responds to all OPTIONS requests with the appropriate CORS related headers (.e.g, Access-Control-Allow-Origin)

Access-Control-Allow-Origin is not working

I've been trying for hours to allow an angularjs client (localhost:5000) to access the resources of a python server using flask (localhost:5001), but I keep receiving the same error message "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5001/api. (Reason: expected 'true' in CORS header 'Access-Control-Allow-Credentials').
So far I've tried to:
Allow CORS via flask_cors using
from flask_cors allow CORS
api = Blueprint('api', __name__)
CORS(api, resources={"/api/*: {"origins": "*"}})
Use angular http-proxy-middleware, both with
server.middleware = proxy('/api', {target: 'http://localhost:5001', changeOrigin:true});
and
server.middleware = proxy('/api', {target: 'http://localhost:5001', changeOrigin:true, onProxyRes: function(proxyRes, req, res){proxyRes.headers['Access-Control-Allow-Origin']='*';}});
The Access-Control-Allow-Origin field in the response header is "http://localhost:5000" and not "http://localhost:5001", which is (if I understand it right), what I need. Any ideas?
I had the same problem and fixed it using the CORS decorator #cross_origin() using the parameter supports_credentials=True (note that you can't use origin='*' and support_credentials=True at the same time)
More infos can be found here

ReactJS fetching API - having CORS error

Sending request from ReactJS app:
fetch(http://my-api-domain, {
method: 'GET',
mode: 'cors', //tried no-cors and same-origin
headers: {
'X-Auth-Token': auth_token' // custom-header
}
}).then(response => console.log(response))
.then(data => {
console.log(data);
}
});
package.json file has "proxy": "http://my-api-domain/"
Then I'm having this error on browser (firefox):
- Cross-Origin Request Blocked: (Reason: missing token ‘x-auth-token’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
- Cross-Origin Request Blocked: (Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
- Cross-Origin Request Blocked: (Reason: CORS request did not succeed).
PS: API server configuration is fine. I've tested my API on Postman. Send GET request with header key: X-Auth-Token; value: [token]. Works fine.
This works in postman because it ignores CORS requests.
If you set 'no-cors' mode, it can still be ignored by the browser, as a security measure. Chrome will most certainly ignore this flag and return you an error.
Solutions:
Whitelist your IP on the api, if it's your api
Set up a reverse proxy such as Nginx that will add allow origin header for you. You will then do a request to a RP, and it will return the response with Allow-Origin header attached for you
Set up a .php or node.js proxy endpoint locally, which will do the same as a RP
Start your browser in no security mode.
Chrome -no security (Windows) example
"C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security

CORS "No 'Access-Control-Allow-Origin' header is present on the requested resource."

I have an error with CORS:
"XMLHttpRequest cannot load http://graphql-swapi.parseapp.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405."
Error when I call a service method.
Code Snippet:
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Methods', 'POST');
headers.append('Access-Control-Allow-Headers', 'Content-Type');
//console.log(headers);
return this._http.post(apiUrl, { query: query, vars: '{}' }, { headers: headers })
.map(res => res.json().data.planets);
When I disable CORS in the browser, I get:
XMLHttpRequest cannot load xxx. Response for preflight has invalid HTTP status code 405 error.
A query and code is for sure correct.
The response had HTTP status code 405
Look that up:
405 Method Not Allowed
Response to preflight request
Look that up:
"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send
Your server side code is, presumably, set up to add the CORS headers to the response to a POST request, but you haven't set it up to handle an OPTIONS request at all.

No 'Access-Control-Allow-Origin' header is present on the requested resource error (angularjs + rest)

Using angularjs to write data in another machine's file failed:
No 'Access-Control-Allow-Origin' header is present on the requested resource
Setting:
anjular js client:
$http.post(url, settingData)
rest server side:
return Response.status(200).entity(jsonObject.toString())
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.allow("OPTIONS")
.build();

Resources