I'm trying to make a Chrome Extension which scrapes some details from Pull Requests on Github using the Fetch API, and then displays them elsewhere. I'm running into some problems when I try to use this with a non-public repository on Github. I believe this is related to CSRF protection, and the rules that govern Chrome extensions having access to session cookies.
I have the following in my extension's manifest.json
:
"content_scripts": [{
"matches": [
"*://github.com/*/*/pulls"
],
"js": ["script/underscore-1.8.3.min.js", "script/content.js"]
}],
"permissions": [
"tabs",
"activeTab",
"*://github.com/*",
"webNavigation"
]
But when I run the following from within my script/content.js
:
fetch('/redacted/redacted/pull/4549', {credentials: 'same-origin'}).then((response) => {
return response.text();
}).then((text) => {
// do cool stuff
})
This produces a 404 response from Github. Inspecting this request with Chrome Inspector's network tab, I can see it is not sending my GitHub session header with the request.
If I make the very same request using the Javascript prompt in the Inspector, I can see a 200 response, and I can see that it is sending my session cookies.
My understanding was that specifying the Github domain in my manifest.json
would mean my extension would have access to my session data in my content scripts, is this not correct? What should I be doing to make a valid request to this protected content?
By default, fetch won’t send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set). Since Aug 25, 2017. The spec changed the default credentials policy to same-origin .
Fetch does not use cookie by default. To enable cookie, do this: fetch (url, { credentials: "same-origin" }).then (...).catch (...); Show activity on this post. In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
What went wrong was that in his case session cookie was not passed along the request to the backend service and the backend replied with http status code 401 — Unauthorized. There are a couple of reasons why the browser would not attach a cookie to the request even if we are expecting it to do so.
@chrisdavidmills Thank you for asking. By default, fetch won’t send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set). Since Aug 25, 2017. The spec changed the default credentials policy to same-origin .
According to Chrome blog, to include cookies you need credentials: 'include'
instead of credentials: 'same-origin'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With