Everyday Dev System

Cookie.get() 이 안될 때 살펴봐야 할 사항 본문

내배캠 주요 학습/TIL : Today I Learned

Cookie.get() 이 안될 때 살펴봐야 할 사항

chaeyoung- 2023. 8. 23. 13:29

 

 

문제점 :

js 파일에서 cookie 값을 조회하려고 하였으나, 조회가 되지 않는 문제가 발생했습니다.

let token = Cookies.get('Authorization'); 
console.log(token);

 

 

시도 : 

 

1. Cookies.get().value를 하여 저장이 되나 시도해 보았습니다,

그럼에도 계속 undefined 로 출력이 되어 해결되지 않았고, 오히려 value로 값을 저장할 수 없다는 에러가 발생했습니다

  let token = Cookies.get('Authorization').value;
  console.log(token);

 

2. 쿠키에 값이 setting이 되지 않은 것은 아닌지 get()을 통해 모두 참조해보았습니다.

이 방법 역시 계속 undefined 로 출력이 잘 됐습니다.

  let cookieResult = Cookies.get();
  console.log(cookieResult);

 

 

계속 시도해본 결과 서버에 요청을 보낼 때 쿠키 값이 헤더에 잘 들어가 있는지 로그을 찍어보았습니다.

 

클라이언트 측 개발자 도구를 열어서 애플리케이션에서 쿠키를 살펴보았습니다.

잘 세팅되어 있었습니다.

 

 

문제가 무엇일까 다시 처음으로 돌아가서 서버코드를 유심히 살펴보았습니다.

jwtUtil 클래스에서 쿠키를 설정하는 메서드 내부를 뜯어보았습니다.

// JWT Cookie 에 access token 저장
  public void addJwtToCookieAccessToken(String token, HttpServletResponse res) {
    token = URLEncoder.encode(token, StandardCharsets.UTF_8).replaceAll("\\+", "%20"); // Cookie Value 에는 공백이 불가능해서 encoding 진행

    Cookie cookie = new Cookie(AUTHORIZATION_HEADER, token); // Name-Value
    cookie.setPath("/");

    cookie.setHttpOnly(true); // For security, make the cookie HttpOnly
    res.addCookie(cookie);
  }

  // JWT Cookie 에 refresh token 저장
  public void addJwtToCookieRefreshToken(String refreshToken, HttpServletResponse res) {
    refreshToken = URLEncoder.encode(refreshToken, StandardCharsets.UTF_8).replaceAll("\\+", "%20"); // Cookie Value 에는 공백이 불가능해서 encoding 진행

    Cookie cookie = new Cookie(REFRESH_HEADER, refreshToken); // refreshToken
    cookie.setPath("/");

    cookie.setHttpOnly(true); // For security, make the cookie HttpOnly
    res.addCookie(cookie);
  }

그러던 중 문제의 요지가 될 듯한 코드를 발견하여 주석 처리를 하고 다시 시도해보았습니다.

 

cookie.setHttpOnly(true); 

 

이 코드가 문제였던 것입니다.

chatGPT에 물어보니..

 

The code cookie.setHttpOnly(true); is not a valid JavaScript function or method call.
It seems like there might be some confusion or misunderstanding.
However, I can explain the concept of the HttpOnly flag when working with cookies.

In the context of cookies, the HttpOnly flag is a security feature that can be set when creating or setting a cookie in a web application.It is a property of a cookie that restricts the cookie from being accessed by JavaScript code running on the client side of the application. In other words, cookies with the HttpOnly flag cannot be accessed or manipulated by JavaScript using the document.cookie API or any other JavaScript method.

요약하면, 해당 코드는 쿠키를 JavaScript function으로 값을 참조할 수 없도록 제한한 코드이다.

쿠키를 생성 및 설정할 때 추가할 수 있는 보안 속성 설정 코드로, JS 파일 내에서 Cookie.get()을 통해 쿠키를 엑세스 할 수 없도록 제한해높은 것이다. 즉, 이와 같이 설정된 쿠키는 JS 코드로 조작할 수 없음을 뜻 합니다.

 

 

 

 

해결방법 : 

서버측에서 JWT 토큰을 설정할 때 

cookie.setHttpOnly(true); 

해당 코드를 삭제하는 방법이 해결 방안이 될 수 있습니다.

 

보안을 강화하기 위해서는 해당 코드를 입력하는 편이 좋습니다.

  public void addJwtToCookieAccessToken(String token, HttpServletResponse res) {
    token = URLEncoder.encode(token, StandardCharsets.UTF_8).replaceAll("\\+", "%20"); // Cookie Value 에는 공백이 불가능해서 encoding 진행

    Cookie cookie = new Cookie(AUTHORIZATION_HEADER, token); // Name-Value
    cookie.setPath("/");

    res.addCookie(cookie);
  }

  public void addJwtToCookieRefreshToken(String refreshToken, HttpServletResponse res) {
    refreshToken = URLEncoder.encode(refreshToken, StandardCharsets.UTF_8).replaceAll("\\+", "%20"); // Cookie Value 에는 공백이 불가능해서 encoding 진행

    Cookie cookie = new Cookie(REFRESH_HEADER, refreshToken); // refreshToken
    cookie.setPath("/");

    res.addCookie(cookie);
  }

 

 

결국 해결되어 js 파일 내에서 console.log()를 찍어보니 정상적으로 잘 출력이 되는 것을 확인할 수 있었습니다.

 

 

 

앞으로 클라이언트 측에서 문제가 생길 때, 클라이언트 측에서만 찾는 것이 아니라

서버에서 설정을 잘 못 한것은 아닌지 먼저 확인해야 할 것 같습니다.