CORS issue with Keyrock - javascript

I'm trying to integrate a custom application with Keyrock Fiware Identity Manager.
The flow is the following:
The user clicks on LOGIN button
He is redirected to the
/oauth2/authorize/?response_type=code&client_id={clientid}&state=xyz&redirect_uri=http:{ip}:{port}
The user inserts his credentials
After the authentication he is redirected to my application where I try to retrieve the token as follow:
var reqData = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + http:{ip}:{port};
var reqHeaders = new Object();
reqHeaders.Access-Control-Allow-Headers= "Content-Type, Access-Control-Allow-Headers,Access-Control-Allow-Origin, Authorization, X-Requested-With, origin, accept",
reqHeaders.Access-Control-Allow-Methods= "POST, GET, OPTIONS, DELETE, PUT",
reqHeaders.Access-Control-Allow-Origin="*"
reqHeaders.Access-Control-Expose-Headers="http://*/*"
reqHeaders.Authorization="Basic {token}"
reqHeaders.Content-Type="application/x-www-form-urlencoded"
reqHeaders.X-Requested-With="XMLHttpRequest"
$.ajax({
url : idmURL + '/oauth2/token',
type : 'POST',
dataType : 'json',
crossDomain : true,
data : reqData,
headers : reqHeaders,
success : function(data) {
console.log(data);
token = data.access_token;
}
});
But the post request never starts because I receive:
XMLHttpRequest cannot load http://{ip}:{port}/oauth2/token. Request header field Access-Control-Allow-Methods is not allowed by Access-Control-Allow-Headers in preflight response.
I've tried to insert the {ip}:{port} to the CORS_WHITELIST and to the ALLOWED_HOST in the local_settings.py file of Keyrock, but nothing changes.
Anyone can help me?

Ironically, I think the issue is caused by the fact that you're using the CORS headers meant for responses in your request:
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Allow-Origin
Access-Control-Expose-Headers
Thus the preflight fails because the server does not allow these, only a subset of headers as provided in the response header Access-Control-Allow-Headers.
Remove these from the request.
For more info: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Related

CORS issue when trying POST

I am getting a CORS issue when trying to use POST with my API.
Access to XMLHttpRequest at 'http://localhost/finalMandatory/api/track/create.php' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I've tried to follow some other posts that seems to have the same issue, but I'm having a hard time implementing it in my own code.
$.ajax({
url: "http://localhost/finalMandatory/api/track/create.php",
type : "POST",
contentType : 'application/json',
data : form_data,
success : function(result) {
showProducts();
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
console.log(form_data);
}
});
I'm also using these headers in my api, which i thought would be enough to deal with CORS problems.
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
I hope someone can help me fix my issue.
I guess that the OPTION request sent to create.php is failing. Maybe because your backend code is trying to perform the action even in this case. OPTION requests should terminate only with CORS headers and an empty body. You can check this with a REST client (Postman for example).

delete request by using FormData returning error 500

i'm working on delete an attachment by send a request with form data containing an URL through an API path with an id
deleteAttachment(id, url) {
const formData = new FormData();
formData.append('url', url);
const config = {
headers: {
'content-type': 'multipart/form-data',
},
};
return Repository.delete(`${resource}/delete-file/${id}`, formData, config);
},
it has no problem with the id and url as i console it and return the right value.
i've test with postman apps by using content-type: json/application and it's says that the request does not have multipart/form-data content-type. then i change the content-type to form-data by key in key = url and value = url and it's successfully deleted. but this deleteAttachment() function did not work and returning this error
xhr.js?b50d:172 DELETE https://anURLPath/api/employee/delete-file/38598 500
Access to XMLHttpRequest at 'https://anURLPath/api/employee/delete-file/38598' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
what's actually happen and the caused of this error? i've used this same code to post API ant it's perfectly worked. but in this delete API is returned the error. can someone help me?
Please add Delete method in Access-Control-Allow-Methods header. POST and GET are added by default but you have to add DELETE method on server side.
"Access-Control-Allow-Methods", "GET, POST, DELETE"

Getting Error while calling external api end point using javascript

I am new to JavaScript and i am trying to send api request from JavaScript.
I am getting below error while calling external endpoint from JavaScript.
from origin 'null' has been blocked by CORS policy: Request header field x-api-key is not allowed by Access-Control-Allow-Headers in preflight response.
var url = "<external_api_for_graphQl"
var api_key = "<api_key>"
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader("x-api-key", api_key);
xhr.send("");
alert(xhr.status);
any idea how we can resolve this?
Thanks
try to set header
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
The Access-Control-Allow-Headers header is sent by the server to let the client know which headers it supports for CORS requests. The value of Access-Control-Allow-Headers should be a comma-delineated list of header names, such as "X-Custom-Information" or any of the standard but non-basic header names (which are always allowed).
This error occurs when attempting to preflight a header that is not expressly allowed (that is, it's not included in the list specified by the Access-Control-Allow-Headers header sent by the server). To fix this, the server needs to be updated so that it allows the indicated header, or you need to avoid using that header.
one think you can try is this:
$.ajax({
headers: { "Accept": "application/json", "x-api-key":"<x-api-key>"},
type: 'POST',
url: '<external_api_for_graphQl>',
crossDomain: true,
beforeSend: function(xhr){
xhr.withCredentials = true;
},
success: function(data, textStatus, request){
console.log(data);
}
});

Request header field Access-Control-Request-Methods is not allowed by Access-Control-Allow-Headers in preflight response

I'm trying to send a POST request from my website to my remote server but I encounter some CORS issues.
I searched in the internet but didn't find a solution to my specific problem.
This is my ajax request params:
var params = {
url: url,
method: 'POST',
data: JSON.stringify(data),
contentType: 'json',
headers: {
'Access-Control-Request-Origin': '*',
'Access-Control-Request-Methods': 'POST'
}
On the backend side in this is my code in python:
#app.route(SETTINGS_NAMESPACE + '/<string:product_name>', methods=['POST', 'OPTIONS'])
#graphs.time_method()
def get_settings(product_name):
settings_data = helper.param_validate_and_extract(request, None, required=True, type=dict, post_data=True)
settings_data = json.dumps(settings_data)
response = self._get_settings(product_name, settings_data)
return output_json(response, requests.codes.ok, headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'
})
I get an error on my console:
XMLHttpRequest cannot load [http://path-to-my-server]. Request header field
Access-Control-Request-Methods is not allowed by
Access-Control-Allow-Headers in preflight response
I did notice that I can add also 'Access-Control-Request-Headers' but I wasn't sure if it necessary and it cause me more problems so I removed it.
Does anyone know how to solve this problem?
Your ajax request shouldn't send Access-Control headers, only the server sends those headers to allow the servers to describe the set of origins that are permitted to read that information using a web browser.
The same-origin policy generally doesn't apply outside browsers, so the server has to send CORS headers or JSONP data if the browser is going to be able to get the data.
The browser doesn't send those headers to the server, it doesn't have to, it's the server that decides whether or not the data is available to a specific origin.
Remove the header option from the params object, and it should work

Microsoft Cognitive Services JavaScript Request 'Access-Control-Allow-Origin'

Hy, when I try to access the Microsoft Cognitive Services API via JavaScript from my server/local machine I get the following error.
XMLHttpRequest cannot load http://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myUrl.com' is therefore not allowed access. The response had HTTP status code 401.
This is my request code:
function requestAPI(){
var params = {
// Request parameters
"visualFeatures": "Categories"
};
$.ajax({
url: "http://api.projectoxford.ai/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{myKey}");
},
type: "POST",
// Request body
data: "{'url':'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
}
In my .htaccess I already added:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
When I test the request with hurl.it it works. Just from my server it doesn't.
Looks like you are setting CORS headers for your server which means someone can make cross-domain request to your server.
Microsoft Cognitive Services have to add these headers on their server so that you can make cross-domain request to them or you have to use JSONP.

Categories

Resources