Skip to content

Commit effa7c9

Browse files
Cors issue
1 parent 670b64d commit effa7c9

1 file changed

Lines changed: 39 additions & 9 deletions

File tree

src/main/java/com/iemr/common/utils/CookieUtil.java

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,45 @@ public Optional<String> getCookieValue(HttpServletRequest request, String cookie
2525
}
2626

2727
public void addJwtTokenToCookie(String Jwttoken, HttpServletResponse response, HttpServletRequest request) {
28-
// Create a new cookie with the JWT token
29-
Cookie cookie = new Cookie("Jwttoken", Jwttoken);
30-
cookie.setHttpOnly(true); // Prevent JavaScript access for security
31-
cookie.setMaxAge(60 * 60 * 24); // 1 day expiration time
32-
cookie.setPath("/"); // Make the cookie available for the entire application
33-
if ("https".equalsIgnoreCase(request.getScheme())) {
34-
cookie.setSecure(true); // Secure flag only on HTTPS
35-
}
36-
response.addCookie(cookie); // Add the cookie to the response
28+
// Create a new cookie with the JWT token
29+
Cookie cookie = new Cookie("Jwttoken", Jwttoken);
30+
31+
// Make the cookie HttpOnly to prevent JavaScript access for security
32+
cookie.setHttpOnly(true);
33+
34+
// Set the Max-Age (expiry time) in seconds (1 day)
35+
cookie.setMaxAge(60 * 60 * 24); // 1 day expiration
36+
37+
// Set the path to "/" so the cookie is available across the entire application
38+
cookie.setPath("/");
39+
40+
// Set the SameSite attribute for cross-site request handling (if needed)
41+
String sameSite = "None"; // Allow cross-site cookies (can be 'Strict', 'Lax', or 'None')
42+
if ("https".equalsIgnoreCase(request.getScheme())) {
43+
// Set Secure flag for HTTPS connection and SameSite=None for cross-site support
44+
cookie.setSecure(true); // Enable cookie only on HTTPS
45+
} else {
46+
cookie.setSecure(false); // No need for Secure flag on HTTP connections
47+
}
48+
49+
// Add the cookie to the response
50+
response.addCookie(cookie);
51+
52+
// Build the Set-Cookie header manually (to add SameSite attribute support)
53+
StringBuilder cookieHeader = new StringBuilder();
54+
cookieHeader.append(cookie.getName()).append("=").append(cookie.getValue())
55+
.append("; Path=").append(cookie.getPath())
56+
.append("; Max-Age=").append(cookie.getMaxAge())
57+
.append("; HttpOnly");
58+
59+
// Add SameSite and Secure attributes manually if needed
60+
cookieHeader.append("; SameSite=").append(sameSite);
61+
if (cookie.getSecure()) {
62+
cookieHeader.append("; Secure");
63+
}
64+
65+
// Set the custom Set-Cookie header
66+
response.addHeader("Set-Cookie", cookieHeader.toString());
3767
}
3868

3969
public String getJwtTokenFromCookie(HttpServletRequest request) {

0 commit comments

Comments
 (0)