Trần Văn Dũng
1 question(s)
0 answer(s)
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 (<a href="https://localhost). " target="_blank">https://localhost). </a> Em có case như sau, khi thực hiện login từ backend em có set cookie như thế này:<div class="markdown-block position-relative overflow-auto source-java"> <pre> private <span class="pl-k">void</span> setTokenCookie(String tokenType, String token, <span class="pl-k">long</span> ttl, HttpServletResponse servletResponse) { <span class="pl-k">if</span> (servletResponse == null) { <span class="pl-k">throw</span> <span class="pl-k">new</span> AppException(ErrorCode.INTERNAL_SERVER_ERROR, "HttpServletResponse is null"); } ResponseCookie tokenCookie = ResponseCookie.from(tokenType, token) .httpOnly(true) .secure(true) .path(<span class="pl-s">"/"</span>) .maxAge(Duration.ofSeconds(ttl)) .sameSite(<span class="pl-s">"None"</span>) .build(); servletResponse.addHeader(<span class="pl-s">"Set-Cookie"</span>, tokenCookie.toString()); } </pre> </div>- Tiếp theo khi thực hiện logout:<div class="markdown-block position-relative overflow-auto source-html"> <pre> const response = await fetch(logoutApiUrl, { method: <span class="pl-s">"POST"</span>, credentials: <span class="pl-s">"include"</span>, headers: { <span class="pl-s">"Content-Type"</span>: <span class="pl-s">"application/json"</span>, Authorization: `Bearer ${localStorage.getItem("accessToken")}`, }, }); </pre> </div><div class="markdown-block position-relative overflow-auto source-java"> <pre> private String extractTokenFromCookie(HttpServletRequest request, String cookieName) { <span class="pl-k">if</span> (request.getCookies() == null) { <span class="pl-k">throw</span> ExceptionUtils.appException(ErrorCode.UNAUTHORIZED, "Cannot find cookies in request header or cookie <span class="pl-s">"</span> + (cookieName.equals(TokenType.ACCESS_TOKEN) ? "access token" : "refresh token")); } <span class="pl-k">for</span> (Cookie cookie : request.getCookies()) { System.out.println(cookie.getName()); <span class="pl-k">if</span> (cookieName.equals(cookie.getName())) { <span class="pl-k">return</span> cookie.getValue(); } } <span class="pl-k">throw</span> ExceptionUtils.appException(ErrorCode.UNAUTHORIZED, "Cannot find cookie with name: %s", cookieName); } </pre> </div>- 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.<p> Mọi người giúp em case này với a? Em cảm ơn ạ! </p>
Answer