I feel like this should be easy but I don't get it.
My React (Next.js) application uses NextAuth.js to obtain a JWT token from an OAuth Provider. Now I need to send this JWT to my backend when doing GraphQL queries, for which I use graphql-request
.
But how can I include the JWT in my GraphQL queries? I could set the header Authorization: Bearer $TOKEN
in my requests, however, the JWT is set as a httpOnly cookie making it unavailable to my react application.
- I could change the settings so that the cookie isn't httpOnly but that would be insecure
- I could get the JWT via NextAuth.js callback and store it in the app's state, but that seems insecure as well
I feel like there should be a way to have the browser add the cookies to my requests. Is that possible? How is this commonly solved?
Update 1
The browser does not send the cookies automatically:
POST /graphql HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 172
sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"
accept: application/json
content-type: application/json
sec-ch-ua-mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36
sec-ch-ua-platform: "Windows"
Origin: http://localhost:3000
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost:3000/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,de;q=0.8,fr;q=0.7
Note that my webapp runs on Port 3000 but GraphQL on 8080. As far as I read, Cookies are not Port-specific and when I open https://localhost:8080 I do see the http://localhost:3000 cookies in Chrome's Developer console.
CodePudding user response:
The browser will automatically send the cookie with request.
CodePudding user response:
Ok so I had to set credentials: "include"
like so:
new GraphQLClient(ENDPOINT, {
headers: {accept: "application/json"},
credentials: "include"
})
Then, I hit CORS Not Supporting Credentials, requiring me to explicitly configure allowed origins on server side.