main-프로젝트/ react-cookie, jwt-decode

Kyoorim LEE·2022년 10월 6일
1

서버에서 보내온 jwt 토큰을 쿠키에 저장하는 방법을 적용해보았다. (저번 프리프로젝트 때는 로컬 스토리지에 저장했었다)

쿠키 관련 함수 작성

설치 : npm install react-cookie

2. src/util/cookie/index.js

setCookie함수를 통해 쿠키를 만들고, getCookie함수를 통해 필요 시 쿠키를 가져오고, removeCookie 함수를 통해 필요 시 쿠키를 지운다

import { Cookies } from 'react-cookie';

const cookies = new Cookies();

export const setCookie = (name: string, value: string, option?: any) => {
  return cookies.set(name, value, { ...option });
};

export const getCookie = (name: string) => {
  return cookies.get(name);
};

export const removeCookie = (name: string) => {
  return cookies.remove(name);
};

각 인자에 대한 설명은 npmjs.com 사이트에 자세히 나와있다.
https://www.npmjs.com/package/react-cookie

name (string): cookie name
value (string|object): save the value and stringify the object if needed
options (object): Support all the cookie options from RFC 6265
path (string): cookie path, use / as the path if you want your cookie to be accessible on all pages
expires (Date): absolute expiration date for the cookie
maxAge (number): relative max age of the cookie from when the client receives it in seconds
domain (string): domain for the cookie (sub.domain.com or .allsubdomains.com)
secure (boolean): Is only accessible through HTTPS?
httpOnly (boolean): Can only the server access the cookie? Note: You cannot get or set httpOnly cookies from the browser, only the server.
sameSite (boolean|none|lax|strict): Strict or Lax enforcement

3. src/apis/index.ts

export const Login = async (LoginForm: ILogin) => {
  try {
    const response = await axios.post('/login', LoginForm, {
      withCredentials: true,
    });
    const jwtToken = response.data;
    setCookie('accessJwtToken', jwtToken); // 쿠키에 토큰 저장
    const decodedUserInfo = jwt_decode(jwtToken); // 토큰 decode
    localStorage.setItem('userInfo', JSON.stringify(decodedUserInfo)); //토큰에 저장되어있는 userInfo 저장
    return response;
  } catch {
    alert('로그인이 실패했습니다. 정보가 올바른지 다시 확인해주세요');
  }
};
  • setCookie 안에 인자로 jwtTokenaccessJwtToken으로 저장하기
  • jwt_decode: 토큰으로 저장된 내용을 decoding해서 localStorage에 userInfo`로 저장하기

    Application 탭에서 확인한 decoded된 토큰

4. src/util/localstorage/index.ts

localStroageuserInfo를 저장하고 필요 시 사용(get) 혹은 삭제(remove)할 수있는 함수를 만든다

import { getCookie, removeCookie } from '../cookie';

export const getUser = () => {
  const userInfo =
    localStorage.getItem('userInfo') && getCookie('accessJwtToken')
      ? JSON.parse(localStorage.getItem('userInfo')!)
      : null;
  return userInfo;
};

export const removeUser = () => {
  removeCookie('accessJwtToken');
  localStorage.clear();
};

5. TopNav에 로그인/로그아웃 상태 표시 및 로그아웃 시 쿠키 삭제하기

...
import { getUser, removeUser } from '../../util/localstorage';

const TopNav = () => {
  const userInfo = getUser();
  ...

  const logoutHandler = () => {
    alert('로그아웃 하시겠습니까?');
    removeUser();
    navigate('/');
  };

  return (
    <S.Container>
      // ...
        </S.Menus>
        {userInfo ? (
          <S.LogOut>
            <h4>반갑습니다 😃</h4>
            <Button onClick={() => navigate('/mypage')}>마이 페이지</Button>
            <Button onClick={logoutHandler}>로그아웃</Button>
          </S.LogOut>
        ) : (
          <S.LogIn>
            <Button onClick={() => navigate('/login')}>로그인</Button>
            <Button onClick={() => navigate('/signup')}>회원가입</Button>
          </S.LogIn>
        )}
		//..
  );
};

export default TopNav;

로그인 하기 전

로그인 후

removeUser()을 통해 로그아웃 시 localStoragecookie에 저장되어있는 토큰 정보가 다 삭제 됨

profile
oneThing

0개의 댓글