Avatar
0
Trần Văn Dũng Beginner
Gửi Nhận Cookie Từ Backend Và Frontend Khác Domain
Xin chào mọi người, hiện tại em làm một project cá nhân chạy trên localhost với spring và html thuần. Ở phía backend(port:8080) và frontend(port:8085) và cả 2 em đều đã cấu hình chạy trên https (https://localhost). Em có case như sau, khi thực hiện login từ backend em có set cookie như thế này:
  private void setTokenCookie(String tokenType, String token, long ttl, HttpServletResponse servletResponse) {
        if (servletResponse == null) {
            throw new AppException(ErrorCode.INTERNAL_SERVER_ERROR, "HttpServletResponse is null");
        }
        ResponseCookie tokenCookie = ResponseCookie.from(tokenType, token)
                .httpOnly(true)
                .secure(true) 
                .path("/")
                .maxAge(Duration.ofSeconds(ttl))
                .sameSite("None")
                .build();

        servletResponse.addHeader("Set-Cookie", tokenCookie.toString());
    }
- Tiếp theo khi thực hiện logout:
     const response = await fetch(logoutApiUrl, {
            method: "POST",
            credentials: "include",
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${localStorage.getItem("accessToken")}`,
            },
          });
private String extractTokenFromCookie(HttpServletRequest request, String cookieName) {
        if (request.getCookies() == null) {
            throw ExceptionUtils.appException(ErrorCode.UNAUTHORIZED, "Cannot find cookies in request header or cookie " + (cookieName.equals(TokenType.ACCESS_TOKEN) ? "access token" : "refresh token"));
        }
        for (Cookie cookie : request.getCookies()) {
            System.out.println(cookie.getName());
            if (cookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        throw ExceptionUtils.appException(ErrorCode.UNAUTHORIZED, "Cannot find cookie with name: %s", cookieName);
    }
- API logout ở backend có gọi đến extractTokenFromCookie để lấy refresh token, em debug thì request.getCookies() luôn là null. Nghĩa là frontend của em chưa nhận được cookie đúng không ạ? Em có tham khảo các bài viết cũng như AI nhưng vẫn chưa tìm được câu trả lời.

Mọi người giúp em case này với a? Em cảm ơn ạ!

  • Answer
Remain: 5
1 Answer
Avatar
tvd12 Enlightened
tvd12 Enlightened
Đúng rồi em ạ, em cần dùng hàm addCookie thay vì servletResponse.addHeader("Set-Cookie", tokenCookie.toString()); nhé, ví dụ:
public static void decorateToAddUserAccessToken(
        HttpServletResponse response,
        UserAccessTokenModel accessToken
    ) {
        response.addCookie(newAccessTokenCookie(accessToken));
        response.addCookie(newAccessTokenExpiredAtCookie(accessToken));
    }
  • 0
  • Reply