[알게된 것] React Native, WebView 로그인 유지

Chobby·2024년 5월 23일
2

알게된 것

목록 보기
53/62

😀문제상황

로그인 후 앱이 종료되었다가 다시 실행되더라도 로그인이 유지가 되어야 하는 상황

😁해결과정

  1. 로그인에 필요한 쿠키를 웹에서 설정(세션)
  2. 앱에서 웹뷰가 종료되기 전 설정된 쿠키들을 모두 저장
  3. 앱이 실행될 경우 설정된 쿠키를 입력

😂문제

  1. http only 된 cookie를 iOS 환경에선 평범한 방법으론 읽어올 수 없었음
    1-1. iOS 전용 메서드인 CookieManager.getAll() 을 통해 읽어올 수 있음을 알게됨
  2. 읽어 온 쿠키를 웹뷰에 적용시킬 방법을 모름
    2-1. CookieManager.set() 메서드를 통해 적용시킬 수 있음을 알게됨

😎주요 코드

import AsyncStorage from '@react-native-async-storage/async-storage';
import CookieManager from '@react-native-cookies/cookies';
...
// 쿠키 불러오기
  const getCookies = async () => {
    try {
      const cookies =
        Platform.OS === 'ios'
          ? await CookieManager.getAll(true)
          : await CookieManager.get(URL);
      const exampleCookie = cookies.(쿠키이름).value
      // cookies.(실제 쿠키 이름).value 로 값을 불러옴
	  if(exampleCookie) await AsyncStorage.setItem('저장될 쿠키 이름', exampleCookie);
    } catch (error) {
      console.error('Failed to get cookies', error);
    }
  };
// 쿠키 웹뷰와 연동
  useEffect(() => {
    const loadCookiesAndSetWebView = async () => {
      const exampleCookie = await AsyncStorage.getItem('저장될 쿠키 이름')
      // WebView에 쿠키를 설정합니다.
      if (!exampleCookie) return;
      await CookieManager.set(URL, {
        name: 'exampleCookie',
        value: exampleCookie,
        path: '/',
        httpOnly: true,
      });
    };

    loadCookiesAndSetWebView();
  }, []);
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글