0
# Cookie Management
1
2
HTTP cookie handling with encoding options, parsing utilities, and header rendering.
3
4
## Capabilities
5
6
### Cookie Class
7
8
Complete HTTP cookie representation with all standard attributes.
9
10
```kotlin { .api }
11
/**
12
* HTTP cookie representation
13
* @param name Cookie name
14
* @param value Cookie value
15
* @param encoding Value encoding method
16
* @param maxAge Maximum age in seconds (null for session cookie)
17
* @param expires Expiration date (null for session cookie)
18
* @param domain Cookie domain
19
* @param path Cookie path
20
* @param secure Secure flag (HTTPS only)
21
* @param httpOnly HttpOnly flag (not accessible to JavaScript)
22
* @param extensions Additional cookie attributes
23
*/
24
data class Cookie(
25
val name: String,
26
val value: String,
27
val encoding: CookieEncoding = CookieEncoding.RAW,
28
val maxAge: Int? = null,
29
val expires: GMTDate? = null,
30
val domain: String? = null,
31
val path: String? = null,
32
val secure: Boolean = false,
33
val httpOnly: Boolean = false,
34
val extensions: Map<String, String?> = emptyMap()
35
) : Serializable {
36
37
/**
38
* Get maxAge as Int (for compatibility)
39
*/
40
val maxAgeInt: Int? get() = maxAge
41
42
companion object {
43
fun serializer(): KSerializer<Cookie>
44
}
45
}
46
```
47
48
### Cookie Encoding
49
50
Enumeration of cookie value encoding methods.
51
52
```kotlin { .api }
53
/**
54
* Cookie value encoding methods
55
*/
56
enum class CookieEncoding {
57
/**
58
* No encoding - value used as-is
59
*/
60
RAW,
61
62
/**
63
* Double-quote encoding - wrap value in quotes
64
*/
65
DQUOTES,
66
67
/**
68
* URI encoding - percent-encode special characters
69
*/
70
URI_ENCODING,
71
72
/**
73
* Base64 encoding - encode value as base64
74
*/
75
BASE64_ENCODING
76
}
77
```
78
79
### Cookie Parsing Functions
80
81
Functions for parsing cookies from HTTP headers.
82
83
```kotlin { .api }
84
/**
85
* Parse Set-Cookie header value into Cookie
86
* @param value Set-Cookie header value
87
* @return Cookie instance
88
*/
89
fun parseServerSetCookieHeader(value: String): Cookie
90
91
/**
92
* Parse Cookie header value into map of name-value pairs
93
* @param value Cookie header value
94
* @param decodeParametersByEncoding Whether to decode values based on encoding
95
* @return Map of cookie names to values
96
*/
97
fun parseClientCookiesHeader(
98
value: String,
99
decodeParametersByEncoding: Boolean = true
100
): Map<String, String>
101
```
102
103
### Cookie Rendering Functions
104
105
Functions for rendering cookies as HTTP header values.
106
107
```kotlin { .api }
108
/**
109
* Render Cookie header value (for client requests)
110
* @param cookie Cookie to render
111
* @return Cookie header value
112
*/
113
fun renderCookieHeader(cookie: Cookie): String
114
115
/**
116
* Render Set-Cookie header value (for server responses)
117
* @param cookie Cookie to render
118
* @return Set-Cookie header value
119
*/
120
fun renderSetCookieHeader(cookie: Cookie): String
121
122
/**
123
* Render Set-Cookie header with individual parameters
124
* @param name Cookie name
125
* @param value Cookie value
126
* @param encoding Value encoding
127
* @param maxAge Maximum age in seconds
128
* @param expires Expiration date
129
* @param domain Cookie domain
130
* @param path Cookie path
131
* @param secure Secure flag
132
* @param httpOnly HttpOnly flag
133
* @param extensions Additional attributes
134
* @param includeEncoding Whether to include encoding attribute
135
* @return Set-Cookie header value
136
*/
137
fun renderSetCookieHeader(
138
name: String,
139
value: String,
140
encoding: CookieEncoding = CookieEncoding.RAW,
141
maxAge: Int? = null,
142
expires: GMTDate? = null,
143
domain: String? = null,
144
path: String? = null,
145
secure: Boolean = false,
146
httpOnly: Boolean = false,
147
extensions: Map<String, String?> = emptyMap(),
148
includeEncoding: Boolean = true
149
): String
150
```
151
152
### Cookie Value Encoding/Decoding
153
154
Functions for encoding and decoding cookie values.
155
156
```kotlin { .api }
157
/**
158
* Encode cookie value using specified encoding
159
* @param value Raw cookie value
160
* @param encoding Encoding method to use
161
* @return Encoded cookie value
162
*/
163
fun encodeCookieValue(value: String, encoding: CookieEncoding): String
164
165
/**
166
* Decode cookie value using specified encoding
167
* @param value Encoded cookie value
168
* @param encoding Encoding method used
169
* @return Decoded cookie value
170
*/
171
fun decodeCookieValue(value: String, encoding: CookieEncoding): String
172
```
173
174
### Date Utilities for Cookies
175
176
Utilities for working with cookie expiration dates.
177
178
```kotlin { .api }
179
/**
180
* Parse cookie date format to GMTDate
181
* @param cookieDate Cookie date string
182
* @return GMTDate instance
183
*/
184
fun fromCookieToGmtDate(cookieDate: String): GMTDate
185
186
/**
187
* Parse HTTP date format to GMTDate
188
* @param httpDate HTTP date string
189
* @return GMTDate instance
190
*/
191
fun fromHttpToGmtDate(httpDate: String): GMTDate
192
193
/**
194
* Format GMTDate as HTTP date string
195
* @param date GMTDate to format
196
* @return HTTP date string
197
*/
198
fun toHttpDate(date: GMTDate): String
199
```
200
201
**Usage Examples:**
202
203
```kotlin
204
import io.ktor.http.*
205
import io.ktor.util.date.*
206
207
// Create basic cookies
208
val sessionCookie = Cookie("session", "abc123")
209
val userCookie = Cookie("user", "john_doe", path = "/", httpOnly = true)
210
211
// Create cookie with expiration
212
val tomorrow = GMTDate(System.currentTimeMillis() + 86400000) // +1 day
213
val persistentCookie = Cookie(
214
name = "remember_me",
215
value = "true",
216
expires = tomorrow,
217
maxAge = 86400, // 1 day in seconds
218
domain = ".example.com",
219
path = "/",
220
secure = true,
221
httpOnly = true
222
)
223
224
// Cookie with encoding
225
val encodedCookie = Cookie(
226
name = "data",
227
value = "special chars: &=;",
228
encoding = CookieEncoding.URI_ENCODING
229
)
230
231
val base64Cookie = Cookie(
232
name = "payload",
233
value = "sensitive data",
234
encoding = CookieEncoding.BASE64_ENCODING
235
)
236
237
// Render cookies for headers
238
val cookieHeader = renderCookieHeader(sessionCookie) // "session=abc123"
239
val setCookieHeader = renderSetCookieHeader(persistentCookie)
240
// "remember_me=true; Max-Age=86400; Expires=Wed, 21 Oct 2024 07:28:00 GMT; Domain=.example.com; Path=/; Secure; HttpOnly"
241
242
// Parse cookies from headers
243
val parsedCookie = parseServerSetCookieHeader("session=abc123; Path=/; HttpOnly")
244
val cookieMap = parseClientCookiesHeader("session=abc123; user=john_doe")
245
// Map: {"session" -> "abc123", "user" -> "john_doe"}
246
247
// Work with cookie encoding
248
val encoded = encodeCookieValue("hello world", CookieEncoding.URI_ENCODING) // "hello%20world"
249
val decoded = decodeCookieValue("hello%20world", CookieEncoding.URI_ENCODING) // "hello world"
250
251
val base64Encoded = encodeCookieValue("secret", CookieEncoding.BASE64_ENCODING) // "c2VjcmV0"
252
val base64Decoded = decodeCookieValue("c2VjcmV0", CookieEncoding.BASE64_ENCODING) // "secret"
253
254
// Cookie with custom extensions
255
val cookieWithExtensions = Cookie(
256
name = "custom",
257
value = "data",
258
extensions = mapOf(
259
"SameSite" to "Strict",
260
"Priority" to "High"
261
)
262
)
263
264
// Date handling
265
val cookieDate = "Wed, 21 Oct 2024 07:28:00 GMT"
266
val gmtDate = fromCookieToGmtDate(cookieDate)
267
val httpDate = toHttpDate(gmtDate)
268
269
// Practical cookie builder
270
fun createSecureCookie(name: String, value: String, domain: String): Cookie {
271
return Cookie(
272
name = name,
273
value = value,
274
domain = domain,
275
path = "/",
276
secure = true,
277
httpOnly = true,
278
maxAge = 86400, // 1 day
279
encoding = CookieEncoding.URI_ENCODING
280
)
281
}
282
283
// Session management example
284
fun createSessionCookie(sessionId: String): String {
285
val cookie = Cookie(
286
name = "JSESSIONID",
287
value = sessionId,
288
path = "/",
289
httpOnly = true,
290
secure = true,
291
maxAge = 1800 // 30 minutes
292
)
293
return renderSetCookieHeader(cookie)
294
}
295
296
// Authentication cookie example
297
fun createAuthCookie(token: String, rememberMe: Boolean): String {
298
val maxAge = if (rememberMe) 86400 * 30 else null // 30 days or session
299
val cookie = Cookie(
300
name = "auth_token",
301
value = token,
302
path = "/",
303
httpOnly = true,
304
secure = true,
305
maxAge = maxAge,
306
encoding = CookieEncoding.BASE64_ENCODING
307
)
308
return renderSetCookieHeader(cookie)
309
}
310
311
// Cookie deletion (set expired date)
312
fun createDeleteCookie(name: String): String {
313
val pastDate = GMTDate(0) // Unix epoch
314
val cookie = Cookie(
315
name = name,
316
value = "",
317
expires = pastDate,
318
maxAge = 0,
319
path = "/"
320
)
321
return renderSetCookieHeader(cookie)
322
}
323
324
// Comprehensive cookie parsing
325
fun parseCookieString(cookieHeader: String): List<Pair<String, String>> {
326
val cookieMap = parseClientCookiesHeader(cookieHeader)
327
return cookieMap.map { (name, value) -> name to value }
328
}
329
```