For the last few weeks, we started getting CORS errors when trying to retrieve the auth token v2 API. We installed chrome CORS plugin and got that to work for now but then the flight fares API started giving CORS errors, we tried providing the regular cors headers in the request but to no avail. here is what is seen in the developer console. I am sending a GET request for the flight fares and tried the regular CORS headers as well but to no avail..
var getFlightFares = {
method: 'GET',
url: mainURL + "/v2/shop/flights/fares",
headers: {
'Authorization': 'Bearer '+token,
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': "/"
//'Access-Control-Allow-Origin': '*',
//'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
//'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
}
};
Result in developer console
GET
http://127.0.0.1:8080/spa/images/flights/sm%7B%7Bcheckout1.returnAirlineCode%7D%7D.gif [HTTP/1.1 200 OK 0ms]
OPTIONS
XHR
https://api.test.sabre.com/v2/auth/token [HTTP/1.1 200 OK 623ms]
POST
XHR
https://api.test.sabre.com/v2/auth/token [HTTP/1.1 200 OK 152ms]
Response :
Object { data: Object, status: 200, headers: dd/<(), config: Object, statusText: "OK" } sabre_integration.js:311:5
tokenT1RLAQJyP+PPcbBSEiIy9JBZrGkt4nu/dBD6CkzcyWI0njOM/Bbn3ngcAADA961ZaE1tN5y/bu57k0DseB5ocYDY9AIj64EwVJOr4RYAHKZF+H8tL7QnM35wjKYr40yjxkp1XL8lRDx84B+whxOMTaDreGnp1tDtFPhCGilvfeFpuXawbf1PjWAsR0uoNE9c0Pnmk8qWwuYEgNEkODYs8+K/peXF97LqylCFC6MWmkyodwSGwH7D/hjD5wTcSqJGLvARwo2NY/hplnArn8rY3sZ9gN3JV5PhqyPks56PYyD0Y5WvABg8YOVEA/Ud sabre_integration.js:312:5
OPTIONS
XHR
https://api.test.sabre.com/v2/shop/flights/fares [HTTP/1.1 404 Not Found 100ms]
Headers
Params
Response
departuredate2016-12-06destinationLAXlengthofstay5originJFKpointofsalecountryUS
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.test.sabre.com/v2/shop/flights/fares?origin=JFK&destination=LAX&departuredate=2016-12-06&lengthofstay=5&pointofsalecountry=US. (Reason: CORS preflight channel did not succeed). (unknown)
GET
http://127.0.0.1:8080/spa/images/flight_listing_sprite.png [HTTP/1.1 200 OK 33ms]
Try opening google chrome from command prompt with the commands:
"chrome.exe --disable-web-security --user-data-dir=/path/to/foo"
check there then
Related
I am trying to send an HTTP Post request from my test method to my Pactnet mock service. The following is the log generated -
[INFO][pact_mock_server::hyper_server] Received request HTTP Request ( method: POST, path: /api/v1/post-txn, query: None, headers: Some({"host": ["127.0.0.1:62047"], "content-length": ["160"], "content-type": ["application/json; charset=utf-8"]}), body: Present(160 bytes, application/json;charset=utf-8) )
[INFO][pact_matching] comparing to expected HTTP Request ( method: POST, path: /api/v1/post-txn, query: None, headers: Some({"Content-Type": ["application/json; charset=utf-8"]}), body: Present(114 bytes, application/json) )
For me, it looks like the received request and the expected request look the same from the log information. However, the test is unsuccessful with the below exception message -
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Access-Control-Allow-Origin: *
x-pact: Request-Mismatch
Date: Thu, 24 Mar 2022 05:16:31 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 648
}}
Could someone help me what is wrong with my received request and expected request, and where there is a mismatch as mentioned in the exception details? I have spent a lot of time debugging, yet I am unable to find what exactly the issue is. Thanks in advance.
If you increase the log level to debug you should be able to compare the JSON body in the request to what's expected. The body looks to be different as I dictated by the number of bytes expected vs actual.
Additionally, there should be an error message to indicate why it failed. If not that could be a bug.
The header content type also looks different on close inspection
I have a woocommerce site and I want its REST API to be open to the world.
I have learned that CORS headers need to be set, so I google and setup the following hook:
add_action('rest_api_init', function() {
remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
add_filter('rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
header('Access-Control-Allow-Headers: Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Origin,Content-Type,X-Auth-Token,Content-Range,Range');
return $value;
});
}, 15);
I confirmed that my server is responding with the correct CORS headers:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers:
Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Origin,Content-Type,X-Auth-Token,Content-Range,Range
Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Then I headed to code the client side:
xhr = new XMLHttpRequest();
xhr.open('POST', 'https://..../wp-json/wc/v3/products');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('mykey:mysecret'));
xhr.send(JSON.stirngify({ ... });
Above code was entered in Chrome console under a https://google.com tab. I just can't get the preflight request to work, here are the errors:
OPTIONS https://..../wp-json/wc/v3/products 401 (Unauthorized)
Access to XMLHttpRequest at 'https://..../wp-json/wc/v3/products' from origin
'https://www.google.com' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: It does not have
HTTP ok status.
Even though the response headers are exactly like posted above.
What am I doing wrong?
if you are using: "Access-Control-Allow-Credentials" = true make sure that "Access-Control-Allow-Origin" is not "*", it must be set with a proper domain!
I'm trying to do a POST request using an access_token, and it works fine using POSTMAN, but when I try to do the same request on Delphi, I can't find a way to add the "Authorization=Bearer eyxxxxxx..." to the Request header, as POSTMAN does.
POSTMAN Request (working well):
POST /somepath HTTP/1.1
Host: someurl.com.br
Authorization: Bearer eyJhbGciOiJSUzI1NiJ9.....
Content-Type: application/json
(body content ommited)
Indy Request generated by Delphi, captured by HTTP Analyzer (always returning 401 Forbidden error, because the absence of "Authorization=Bearer" part):
POST /somepath HTTP/1.1
Host: someurl.com.br
Content-Type: application/json
(body content ommited)
I've tried to add the header using the code below, but the header part with the "Authorization=Bearer eyxxxxxx..." isn't generated on Request, returning the 401 Forbidden error.
FIdHTTP.Request.CustomHeaders.FoldLines := False;
FIdHTTP.Request.CustomHeaders.Add('Authorization=Bearer ' + txtToken.Text);
Just found the problem. I added the wrong separator between the "Authorization" and "Bearer" words.
Wrong:
FIdHTTP.Request.CustomHeaders.FoldLines := False;
FIdHTTP.Request.CustomHeaders.Add('Authorization=Bearer ' + txtToken.Text);
Correct:
FIdHTTP.Request.CustomHeaders.FoldLines := False;
FIdHTTP.Request.CustomHeaders.Add('Authorization:Bearer ' + txtToken.Text);
After replacing the '=' by ':', I received the expected response, like the one received by POSTMAN.
I have this NodeJS snippnet :
require('http').get({
secure: true,
host: 'github.com',
method: 'GET',
path: '/downloads/Graylog2/graylog2-web-interface/graylog2-web-interface-0.9.6.tar.gz',
'headers': {
Host: 'github.com'
}}).on('response', function(response) {
console.log(response.statusCode);
});
It is suppose to do a simple GET request on https://github.com/downloads/Graylog2/graylog2-web-interface/graylog2-web-interface-0.9.6.tar.gz (sample)
The problem I face is the HTTP status, using the NodeJS client I have 301 Moved Permanently. I am expected a 302 Found (actually what I get with Chrome, cUrl, http://web-sniffer.net,...).
Thanks
There is no secure option for request. What you want is to instead use the https module.
require('https')
I'm trying to use the API on a website, here's the part of the manual:
Authenticated Sessions (taken from here)
To create an authenticated session, you need to request an authToken from the '/auth' API resource.
URL: http://stage.amee.com/auth (this is not my domain)
Method: POST
Request format: application/x-www-form-urlencoded
Response format: application/xml, application/json
Response code: 200 OK
Response body: Details of the authenticated user, including API
version.
Extra data: "authToken" cookie and header, containing the
authentication token that should be
used for subsequent calls.
Parameters: username / password
Example
Request
POST /auth HTTP/1.1
Accept: application/xml
Content-Type: application/x-www-form-urlencoded
username=my_username&password=my_password
Response
HTTP/1.1 200 OK
Set-Cookie: authToken=1KVARbypAjxLGViZ0Cg+UskZEHmqVkhx/Pm...;
authToken: 1KVARbypAjxLGViZ0Cg+UskZEHmqVkhx/PmEvzkPGp...==
Content-Type: application/xml; charset=UTF-8
QUESTION:
How do I get that to work?
I tried jQuery, but it seems to have problem with XSS. Actual code snippet would be greatly appreciated.
p.s.
All I was looking for was WebClient class in C#
You need to put application/json in your Accept header, this tells the server you want it to respond in that format - not xml.
I am using rails to extract the same authentication token cookie from stage.amee.com/auth as mentioned above. it took a bit of experimentation before I created and customised the correct request object that returned a 200 OK, with the authtoken as a cookie. i haven't found an effective method of reading the request object or I would post exactly what it looks like. here is my ruby code from the app's controller
#define parameters
uri=URI.parse('http://stage.amee.com')
#path = '/auth'
#login_details = 'username=your_username&password=your_password'
#headers = {'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json'}
#create request object
req = Net::HTTP.new(uri.host, uri.port)
#send the request using post, defining the path, body and headers
resp, data = req.post(#path, #login_details, #headers)
#print response details to console
puts "response code = " << resp.code
puts "response inspect = " << resp.inspect
resp.each do |key, val|
puts "response header key : " + key + " = " + val
end
puts "data: " + data