2

My script will not store a cookie that is coming from an API.

My function is able to get send a user/pass to the API, and it gets the body of the response from the API. However the cookie does not get stored in the browser.

The API is offering the Cookie, I have confimed this by making the request with curl. I can see a cookie header in the response. < Set-Cookie: id=abcdefXXX; HttpOnly>

I need the cookie in order to access other APIs.. ( it is an access token )

What do i need to do, to get fetch to save the cookie.

async function get_aws_token(user,password)
    {
        data = {'username': user, 'password':password };
        let myAuth =  await fetch('https://XXXXXXX.execute-api.ap-southeast-2.amazonaws.com/prod/auth',
         {
            method: 'PUT',
            headers: { 'content-Type': 'application/json'}, 
            credentials: 'same-origin',     
            body: JSON.stringify(data),
         });
         //console.log(myAuth);
         let myResponse = await myAuth.json()
         if ('errorMessage' in myResponse )
            {
              output = 'Invalid Login';
            }
          else if (myResponse["status"] = 'success')
            {
              output = 'Good Login';
              // redirect to a new page
              //window.open ('usermenu.htm','_self',false)

            }
          else 
            {
              output = 'Unable to Connect to Authorisation Service'
            }
          document.getElementById("outputtext").innerHTML = output;
      }

I woudl have expected the cookie to end up being avaialble to the broswer, but it is not.

These are the headers that i get when looking from curl.

< HTTP/1.1 200 OK
< Date: Mon, 19 Aug 2019 04:08:30 GMT
< Content-Type: application/json
< Content-Length: 3709
< Connection: keep-alive
< x-amzn-RequestId: 00b3963f-c237-11e9-b0e7-3fa61b7c463b
< Access-Control-Allow-Origin: http://127.0.0.1:5500
< Set-Cookie: id_token=eyJraW..........QiOiJ; HttpOnly
< x-amz-apigw-id: epoNuETVSwMFXqg=
< X-Amzn-Trace-Id: Root=1-5d5a20be-6a06f022cf479ef3b96da240;Sampled=0
< Access-Control-Allow-Credentials: true
  • read [fetch documentation](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) - specifically *By default, fetch won't send or receive any cookies from the server* – Jaromanda X Aug 19 '19 at 03:55
  • putting credentials: 'same-origin', did'nt seem to make any difference. The sever is also providing anotehr header "Access-Control-Allow-Credentials: true" – user3547535 Aug 19 '19 at 04:12
  • is the request "same origin"? Anyway, nothing in the fetch documentation seems to indicate that cookies are ever ***received*** by fetch - unless I'm reading it wrong – Jaromanda X Aug 19 '19 at 04:29

0 Answers0