I'm trying to get the response header of a website and get the cookies that i can find inside. There is no problem, it's working when i start the request through a terminal with "node file.js".
But i'm launching the POST request through a local HTML page, so i used browersify for be able to launch a request from a client-side (or at least this is what i understood).
Then i'm using a CORS proxy to get around “No Access-Control-Allow-Origin header” problems. When i start the request from my local HTML page it's working and i can read the body but i'm not able to find the reponse header of the website and get the cookie that i need.
Here how my request looks like:
function connectionInfoConcert(account, psw, next){
console.log("-------------CREATE HEADER-------------\n")
var options = {
method: 'POST',
url: 'https://tranquil-thicket-71867.herokuapp.com/https://www.infoconcert.com/mon-infoconcert/connexion.html',
headers: {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Language':'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Content-Length':'184',
'Content-Type':'application/x-www-form-urlencoded',
'origin': 'https://www.infoconcert.com',
'referer': 'https://www.infoconcert.com/mon-infoconcert/connexion.html'
},
form: {
origin:'',
username: account,
password: psw
}
};
console.log("-------------END HEADER-------------\n-----------START REQUEST-----------------------")
request(options, function (error, response, body) {
if (!error) {
console.log(response)
console.log(body)
console.log(response.headers['set-cookie'][0]); //obviously 'set-cookie' doesn't exist
}
else {
console.log(error)
console.log(response)
console.log("-------------ERROR------------")
return console.log("Something went wrong")
}
});}
https://www.infoconcert.com/mon-infoconcert/connexion.html is the website where i try to get the cookie
https://tranquil-thicket-71867.herokuapp.com is the CORS proxy that i'm using.
If some of you know how to be able to get the correct header it would be really nice !
Edit 1 :
The problem is when i do my request to "https://www.infoconcert.com/mon-infoconcert/connexion.html" i can find the cookie that i'm looking for in response.headers["set-cookie"].
But because i'm doing the request from a html page it's not working and i'm doing the request to "https://tranquil-thicket-71867.herokuapp.com/https://www.infoconcert.com/mon-infoconcert/connexion.html" but i can't find my cookie in the response.
Here the header of the response i got from "https://tranquil-thicket-71867.herokuapp.com/https://www.infoconcert.com/mon-infoconcert/connexion.html"
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: server,vary,cache-control,content-type,content-encoding,p3p,date,expires,pragma,connection,x-cache-info,x-final-url,access-control-allow-origin
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html; charset=UTF-8
Date: Thu, 03 May 2018 17:23:49 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
P3p: policyref="/w3c/p3p.xml", CP="NOI DSP COR NID CUR ADM DEV OUR BUS"
Pragma: no-cache
Server: Apache
Transfer-Encoding: chunked
Vary: Accept-Encoding,User-Agent
Via: 1.1 vegur
X-Cache-Info: not cacheable; response specified "Cache-Control: private"
X-Cors-Redirect-1: 302 https://www.infoconcert.com/mon-infoconcert/index.html
X-Cors-Redirect-2: 302 https://www.infoconcert.com/mon-infoconcert/connexion.html
X-Final-Url: https://www.infoconcert.com/mon-infoconcert/connexion.html
X-Request-Url: https://www.infoconcert.com/mon-infoconcert/connexion.html
So i think it's my proxy who doesn't forward the cookie that he gets.
If you need more details just ask.
Thanks you very much for your help
Related
I'm developing a web app and there is already a login system that keep the session through a cookie. Now i would like to implement logout function. My idea was to delete cookie session but even if i clear cookies in every way when node express send back a response, cookies are auto-set.
I really don't know why. I'm using node express server with passport for login with Google, express-session, React for front end, axios for requests.
This is my request from Client:
const Logout = ({ login, setLogin}:Props ) => {
useEffect(() => {
const _response = axios({
method: 'get',
url: `http://127.0.0.1:3002/auth/logout`,
withCredentials: true,
}).then(res => {
if(res.data === 'ok') setLogin(false)
console.log(res.headers['session']);
// window.location.replace('/projects')
})
}, [])
return (<></>);
}
And this is how i get response from Server:
router.get("/logout", (req, res, next) => {
res.clearCookie('session')
res.setHeader('Set-Cookie', 'ppp')
res.cookie('Set-Cookie', 'ZZZ', { maxAge: 900000, httpOnly: true })
res.send('ok')
});
As you can see below on the response headers i have multiple cookies 'Set-Cookie', but the last one is being inserted by default (?), and i don't know by who and why.
I tried to send different request with axios and fetch methods, changing GET with POST and so on but anything.
Having a cookie session it doesnt let me to effectively log-out. I think the solution is to delete that cookie so i can log with another gmail account. If there are better solution please let me know.
Thanks for everyone who can help me!
General:
URL di richiesta: http://127.0.0.1:3002/auth/logout
Metodo di richiesta: GET
Codice di stato: 200 OK
Indirizzo remoto: 127.0.0.1:3002
Criterio relativo al referrer: strict-origin-when-cross-origin
Response Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
Content-Length: 2
Content-Type: text/html; charset=utf-8
Date: Mon, 20 Feb 2023 08:51:14 GMT
ETag: W/"2-eoX0dku9ba8cNUXvu/DyeabcC+s"
Set-Cookie: ppp
Set-Cookie: Set-Cookie=ZZZ; Max-Age=900; Path=/; Expires=Mon, 20 Feb
2023 09:06:14 GMT; HttpOnly
Set-Cookie:
session=s%3AVtFyrI9jABANw_5oY09xDlYulRwJZaT1.aaJWZJeCHRDU6XGgJMu7Zgs1axAIdVYMurucpvKnJ3c; Path=/; Expires=Mon, 20 Feb 2023 11:15:14 GMT; HttpOnly
Vary: Origin
X-Powered-By: Express
Request headers:
Accept: application/json, text/plain, /
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,it;q=0.7
Connection: keep-alive
Host: 127.0.0.1:3002
If-None-Match: W/"2-eoX0dku9ba8cNUXvu/DyeabcC+s"
Origin: http://localhost:3000
Referer: http://localhost:3000/
sec-ch-ua: "Chromium";v="106", "Google Chrome";v="106", "Not;A=Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Linux"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36
The second Set-Cookie header in your response:
Set-Cookie=ZZZ; Max-Age=900; Path=/; Expires=Mon, 20 Feb 2023 09:06:14
GMT; HttpOnly
Has the cookie name as Set-Cookie instead of a valid cookie name. This is causing the client to treat it as a new cookie, and therefore adding a third Set-Cookie header for the session cookie.
And why do you do that :
res.setHeader('Set-Cookie', 'ppp')
It should be someting like that :
res.setHeader('Set-Cookie', 'name=value')
You can, to clean that, replace :
res.setHeader('Set-Cookie', 'ppp')
res.cookie('Set-Cookie', 'ZZZ', { maxAge: 900000, httpOnly: true })
By
res.cookie('ppp', 'cookieValue');
res.cookie('ZZZ', '{ maxAge: 900000, httpOnly: true }');
I'm trying to make a GET query using Fetch but I'm getting an error 404 when passing the Authorization.
I don't know why this error happens because the server responds well when I use a tool like Postman.
Authorization: Basic ...
method: GET
url: https://zammad.zonngo.com/api/v1/ticket_articles
When I use Javascript fetch API the error 404 appears.
OPTIONS https://zammad.zonngo.com/api/v1/ticket_articles 404 (Not Found)
There's my code:
const myHeaders = new Headers();
myHeaders.append('Authorization','Basic ...');
myHeaders.append('Content-Type','application/json');
fetch(URLTICKETS, {
method: 'GET',
headers: myHeaders
})
.then(response => {
console.log(response);
})
.then(error => {
console.log(error);
});
Would be nice if anyone can help me.
The GET method on the URL returns a 401 status code but the OPTIONS method actually returns a 404.
http OPTIONS https://zammad.zonngo.com/api/v1/ticket_articles
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html; charset=UTF-8
Date: Thu, 02 Nov 2017 01:37:59 GMT
Server: nginx/1.10.3 (Ubuntu)
Transfer-Encoding: chunked
X-Request-Id: 16f58319-2658-4b0e-824c-08ca68e8d401
X-Runtime: 0.003135
The OPTIONS is probably caused by a CORS preflight request which does not seem to be handled correctly by https://zammad.zonngo.com/.
https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
SO my graphql api is at https://gpbaculio-tributeapp.herokuapp.com/graphql I configured the uploaded, headers like this:
const fetchQuery = (operation, variables) => {
return fetch('/graphql', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
return response.json()
})
}
I have read from MDN.
For requests without credentials, the server may specify "*" as a
wildcard, thereby allowing any origin to access the resource.
So I am trying to publish the app in codepen, and this is my error:
Failed to load https://gpbaculio-tributeapp.herokuapp.com/graphql:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://s.codepen.io'
Why is it telling me it doesn't pass 'Access-Control-Allow-Origin' headers?
Is there something wrong with my headers config?
You are setting the header in your request (in the client). The Access-Control-Allow-Origin header needs to be set on the server-side, and when you make a request, the response should contain that header.
The reason behind this header is that not every webpage can query every third-party domain. Being able to set this header from the request would defeat that whole point.
Try setting cors options and Access-Control-Allow-Origin headers in server side.
const graphQLServer = express();
const corsOptions = {
origin(origin, callback) {
callback(null, true);
},
credentials: true
};
graphQLServer.use(cors(corsOptions));
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
graphQLServer.use(allowCrossDomain);
This may help you
CORS specification states, that requests for resources are "preflighted" with HTTP OPTIONS request, and reply headers for that OPTIONS must contain header:
Access-Control-Allow-Origin: *
you might check it with curl:
$ curl -I -X OPTIONS https://gpbaculio-tributeapp.herokuapp.com/graphql
HTTP/1.1 405 Method Not Allowed
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Allow: GET, POST
Content-Type: application/json; charset=utf-8
Content-Length: 97
Date: Sat, 23 Sep 2017 11:24:39 GMT
Via: 1.1 vegur
Add OPTION handler with needed header, so your server answers:
$ curl -I -X OPTIONS https://example.localhost/
HTTP/1.1 204 No Content
Server: nginx/1.4.7
Date: Sat, 23 Sep 2017 11:27:51 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range
Content-Type: text/plain; charset=utf-8
Content-Length: 0
The problem is the browser's cross-origin problem.
The Access-Control-Allow-Origin header should be return by the server's response, and the header means the origin domain that can access to the API.
The client's request often take a header Origin, it's value is the current host address, like, www.example.com.
The values of Access-Control-Allow-Origin must contain the value of Origin means that the origin can access this API service. And then the browser will continue the request. If not, the browser will cancel the request.
More infomation, refre to CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
I'm developing an Azure MobileService / CordovaApp setup. The server runs locally and has the following setting to enable CORS:
<add name="Access-Control-Allow-Origin" value="*" />
The api can be called via browser using addresses like
http://localhost:59477/api/item/explore/A/B
The client script that's trying to depict this call is the following:
var client = new WindowsAzure.MobileServiceClient('http://localhost:59477/', 'http://localhost:59477/', '');
GetItems.addEventListener("click",
function ()
{
client.invokeApi("item/explore/A/B",
{
method: "get"
})
.done(
function (results)
{
alert(results.result.count);
},
function (error)
{
var xhr = error.request;
alert('Error - status code: ' + xhr.status + '; body: ' + xhr.responseText);
alert(error.message);
}
);
}
);
What I get is status 405 - Method not allowed, which I don't understand for two reasons:
The invoked Service Action is decorated with the [HttpGet] Attribute
The response headers seem to say GET is fine:
HTTP/1.1 405 Method Not Allowed
Allow: GET
Content-Length: 76
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-SourceFiles: =?UTF-8?B?RjpcQ29kZVxGb290UHJpbnRzXGZvb3RwcmludHMuU2VydmVyXEZvb3RwcmludHNTZXJ2aWNlXGFwaVxmb290cHJpbnRcZXhwbG9yZVw1MS4yNzcwMjJcNy4wNDA3ODM=?=
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Date: Sat, 15 Aug 2015 18:08:30 GMT
Any idea what I can do to get this running?
Edit
The Raw request shows that, as already expected by Jeremy Foster, the client sends a request of the type OPTIONS:
OPTIONS http://localhost:59477/api/fp/get?id=1 HTTP/1.1
Host: localhost:59477
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:4400
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Access-Control-Request-Headers: accept, x-zumo-features, x-zumo-installation-id, x-zumo-version
Accept: */*
Referer: http://localhost:4400/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
I managed to support this request applying the [HttpOptions] attribute to my action method. Now I get a more or less valid response:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-SourceFiles: =?UTF-8?B?RjpcQ29kZVxGb290UHJpbnRzXGZvb3RwcmludHMuU2VydmVyXEZvb3RwcmludHNTZXJ2aWNlXGFwaVxmcFxnZXRcMQ==?=
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Date: Sun, 23 Aug 2015 19:34:21 GMT
Content-Length: 234
...
At least that's what fiddler tells me. The AzureMobileServiceClient throws yet another issue, which roughly translates as:
Cross-Origin request blocked, missing token 'x-zumo-installation-id' in CORS header row 'Access-Control-Allow-Headers' on CORS-Preflight-Channel
Turn on Fiddler and try your api call from the browser and then again using the Mobile Services client and compare your raw HTTP requests to see what's different.
Try to run through the CORS Support section of this blog post: http://azure.microsoft.com/blog/2014/07/28/azure-mobile-services-net-updates/.
A side note: The x-zumo-installation-id error you were getting was because the client requested access for a list of headers (see the Access-Control-Request-Headers in your request) and the server did not return that same list in the Access-Control-Allow-Headers header. Using the MS_CrossDomainOrigins setting as mentioned in the above blog post takes care of this by setting the allowed headers to * (all) by default.
Okay, I've looked all over for this. Basically we're using $http request that ARE cross domain requests. Our server allows the domain and when a request returns 200, everything is OK. However, anytime our server returns an error, 500, 401, whatever, Angular thinks it's a CORS issue.
I debugged the response with Fiddler to verify my server IS returning a 500, yet Angular chokes on it.
Here's the request:
var params = {
url: "fakehost/example",
method: 'GET',
headers: {
"Authorization": "Basic encodedAuthExample"
}
};
$http(params).then(
function (response) { // success
},
function (error) { // error
// error.status is always 0, never includes data error msg
});
Then in the console, I will see this:
XMLHttpRequest cannot load fakehost/example. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'mylocalhost:5750' is therefore not allowed access.
Yet, in fiddler, the true response is:
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 26 Aug 2014 12:18:17 GMT
Content-Length: 5683
{"errorId":null,"errorMessage":"Index was outside the bounds of the array.","errorDescription":"Stack trace here"}
I'm on AngularJS v1.2.16
I think I found an answer, looks like you will have to inject in your asp.net pipeline the correct CORS headers, as mentioned here.