httponly cookie
what is http only cookie
ChatGPT said:
🍪 What is an HttpOnly Cookie?
An HttpOnly cookie is a type of cookie that cannot be accessed via JavaScript (i.e., document.cookie), and can only be sent in HTTP requests between the client and the server.
🧠 Why is it used?
To protect sensitive data—especially tokens like JWTs or session IDs—from Cross-Site Scripting (XSS) attacks.
✅ Key Properties of an HttpOnly Cookie
| Property | Description |
| HttpOnly | Can't be accessed via document.cookie (JavaScript can't read or manipulate it) |
| Secure | (optional) Sent only over HTTPS connections |
| SameSite | Controls whether the cookie is sent in cross-origin requests |
| Path/Domain | Controls the scope of the cookie |
📦 Example (Set-Cookie header):
When the server sets a cookie:
pgsqlCopyEditSet-Cookie: token=abc123; HttpOnly; Secure; SameSite=Strict; Path=/
📤 How it Works in Practice
✅ Server sets it like:
httpCopyEditSet-Cookie: jwt=your_token; HttpOnly; Secure; SameSite=Lax
✅ Client:
Browser stores it
Automatically sends it with requests to the backend
❌ JavaScript on the page:
jsCopyEditconsole.log(document.cookie); // ❌ jwt won't appear if HttpOnly is set
🛡️ Why It’s Important for Security
| Attack Type | HttpOnly Helps? | Explanation |
| XSS | ✅ Yes | JS can't steal token |
| CSRF | ❌ No (use SameSite=Strict + CSRF tokens) | Cookies still auto-send on cross-origin unless protected |
✅ Use Case in Auth (Example)
If you're using Spring Boot with cookies for auth:
javaCopyEditResponseCookie.from("jwt", token)
.httpOnly(true)
.secure(true)
.path("/")
.maxAge(Duration.ofDays(7))
.build();
🧠 Summary
| Feature | HttpOnly Cookie |
| Accessible via JS | ❌ No |
| Sent in HTTP Req | ✅ Yes |
| Prevents XSS | ✅ Yes |
| Prevents CSRF | ❌ No (use SameSite + token) |
Let me know if you want a Spring Boot or frontend example using HttpOnly JWT cookies!
You said:
how to send httponly cookie from springboot
ChatGPT said:
To send an HttpOnly cookie (such as a JWT) from a Spring Boot backend, you typically do this after successful authentication — for example, during login or OAuth.
Here’s a step-by-step guide to sending an HttpOnly cookie in Spring Boot.
✅ Step 1: Generate the Token (e.g., JWT)
You’ll usually have a JwtService to create your token:
javaCopyEditString jwt = jwtService.generateToken(userDetails);
✅ Step 2: Create the HttpOnly Cookie
Use Spring’s ResponseCookie to create a secure cookie:
javaCopyEditimport org.springframework.http.ResponseCookie;
ResponseCookie cookie = ResponseCookie.from("jwt", jwt)
.httpOnly(true) // ✅ Prevent JS access
.secure(true) // ✅ Only send over HTTPS (recommended for prod)
.path("/") // ✅ Send on all endpoints
.maxAge(Duration.ofDays(7)) // ✅ Cookie expiration
.sameSite("Lax") // ✅ Prevent CSRF (Lax/Strict/None)
.build();
✅ Step 3: Send It via the Response
Attach it to the response header like this:
javaCopyEditreturn ResponseEntity.ok()
.header(HttpHeaders.SET_COOKIE, cookie.toString())
.body("Login successful");
🔄 Full Example: AuthController.java
javaCopyEdit@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest request) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword())
);
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String jwt = jwtService.generateToken(userDetails);
ResponseCookie cookie = ResponseCookie.from("jwt", jwt)
.httpOnly(true)
.secure(true) // use HTTPS in production
.path("/")
.maxAge(Duration.ofDays(7))
.sameSite("Lax")
.build();
return ResponseEntity.ok()
.header(HttpHeaders.SET_COOKIE, cookie.toString())
.body("Login successful");
}
⚠️ Frontend Notes
To allow the frontend to receive and send the HttpOnly cookie:
✅ In React/Vite/Axios/Fetch:
jsCopyEditfetch("http://localhost:8080/login", {
method: "POST",
credentials: "include", // Important: send/receive cookies
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
});
Use
credentials: "include"to allow cookies to be sent and received between frontend & backend.
✅ Bonus: Enable CORS to Allow Cookies
Spring Security config must allow credentials:
javaCopyEdit@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000") // React frontend URL
.allowedMethods("*")
.allowCredentials(true); // ✅ important
}
};
}
🧠 Summary
| Task | Code |
| Generate JWT | jwtService.generateToken() |
| Create HttpOnly Cookie | ResponseCookie.from(...).httpOnly(true) |
| Send via header | header(HttpHeaders.SET_COOKIE, cookie.toString()) |
| Frontend support | credentials: "include" in fetch/Axios |
| CORS config | allowCredentials(true) |
Let me know if you'd like logout (delete cookie), or access protected routes with the HttpOnly cookie!