简体   繁体   中英

Access cookies in a react app hosted on AWS Cloudfront-S3

I have a react project hosted on AWS S3 bucket & served through Cloudfront . Also, it is integrated with API Gateway to authorize the user visiting my react app. As soon as the user is authorized, it is being redirected to the dashboard, with his/her credentials info stored in the form of cookies into the browser.

The format of the cookies look like this:

在此处输入图片说明

I need to access those cookies (idToken to be specific) from the browser and sent it further as the Auth Token inside the header of the backend request.

I tried using the npm package react-cookies , but it doesn't seems to work. It keeps throwing an error:

TypeError: Cannot read property 'load' of undefined .

I tried the following approach:

import cookie  from 'react-cookie';

const getCookies = () => {
    const auth_token = cookie.get('CognitoIdentityServiceProvider.1an******************************133.idToken', {
        httpOnly: false
    });

    console.log('auth token extracted', auth_token);
}

export default getCookies;

I am very much new to handling cookies & auth on AWS. If any help to resolve the same, will be appreciated.

For getting the cookie, instead of using library you can write a function and pass the key name.

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

So in your case you can get the value by calling the function and passing the key. as Andre mentioned in the comment, the cookie stores in the browser. So you can access it through document.cookie

For example in your case.

// console.log(getCookie('CognitoIdentityServiceProvider.1an******************************133.idToken'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM