0
# Cookie Management
1
2
Cookie storage and management with configurable storage backends, automatic cookie handling, and support for session management.
3
4
## Capabilities
5
6
### HttpCookies Plugin
7
8
Core plugin for automatic cookie management with configurable storage.
9
10
```kotlin { .api }
11
/**
12
* HTTP cookies management plugin
13
*/
14
class HttpCookies private constructor(
15
private val storage: CookiesStorage
16
) : Closeable {
17
/**
18
* Cookie plugin configuration
19
*/
20
class Config {
21
/** Cookie storage implementation */
22
var storage: CookiesStorage = AcceptAllCookiesStorage()
23
24
/**
25
* Add default cookies to storage
26
*/
27
fun default(block: suspend CookiesStorage.() -> Unit)
28
}
29
30
companion object : HttpClientPlugin<Config, HttpCookies> {
31
override val key: AttributeKey<HttpCookies> = AttributeKey("HttpCookies")
32
}
33
34
/**
35
* Get cookies for specific URL
36
*/
37
suspend fun get(requestUrl: Url): List<Cookie>
38
39
override fun close()
40
}
41
```
42
43
**Usage Examples:**
44
45
```kotlin
46
import io.ktor.client.plugins.cookies.*
47
import io.ktor.http.*
48
49
val client = HttpClient {
50
install(HttpCookies) {
51
// Use default storage (accepts all cookies)
52
storage = AcceptAllCookiesStorage()
53
54
// Add default cookies
55
default {
56
addCookie("https://api.example.com", Cookie("session", "abc123"))
57
addCookie("https://api.example.com", Cookie("theme", "dark"))
58
}
59
}
60
}
61
62
// Cookies are automatically handled
63
val response1 = client.get("https://api.example.com/login") {
64
// Server sets cookies in response
65
}
66
67
// Cookies automatically sent with subsequent requests
68
val response2 = client.get("https://api.example.com/profile") {
69
// Cookies from previous response are included
70
}
71
```
72
73
### CookiesStorage Interface
74
75
Interface for cookie storage implementations with lifecycle management.
76
77
```kotlin { .api }
78
/**
79
* Interface for cookie storage implementations
80
*/
81
interface CookiesStorage : Closeable {
82
/**
83
* Get cookies for specific URL
84
*/
85
suspend fun get(requestUrl: Url): List<Cookie>
86
87
/**
88
* Add cookie for specific URL
89
*/
90
suspend fun addCookie(requestUrl: Url, cookie: Cookie)
91
92
override fun close()
93
}
94
95
/**
96
* Extension function for adding cookies with URL string
97
*/
98
suspend fun CookiesStorage.addCookie(urlString: String, cookie: Cookie) {
99
addCookie(Url(urlString), cookie)
100
}
101
```
102
103
### Built-in Storage Implementations
104
105
Pre-built cookie storage implementations for common use cases.
106
107
```kotlin { .api }
108
/**
109
* Storage that accepts and stores all cookies
110
*/
111
class AcceptAllCookiesStorage : CookiesStorage {
112
override suspend fun get(requestUrl: Url): List<Cookie>
113
override suspend fun addCookie(requestUrl: Url, cookie: Cookie)
114
override fun close()
115
}
116
117
/**
118
* Storage with constant predefined cookies
119
*/
120
class ConstantCookiesStorage(cookies: List<Cookie>) : CookiesStorage {
121
override suspend fun get(requestUrl: Url): List<Cookie>
122
override suspend fun addCookie(requestUrl: Url, cookie: Cookie) {
123
// No-op - constants cannot be modified
124
}
125
override fun close()
126
}
127
```
128
129
**Usage Examples:**
130
131
```kotlin
132
// Accept all cookies (default)
133
val client1 = HttpClient {
134
install(HttpCookies) {
135
storage = AcceptAllCookiesStorage()
136
}
137
}
138
139
// Constant cookies only
140
val constantCookies = listOf(
141
Cookie("auth_token", "xyz789"),
142
Cookie("user_preference", "compact_view")
143
)
144
145
val client2 = HttpClient {
146
install(HttpCookies) {
147
storage = ConstantCookiesStorage(constantCookies)
148
}
149
}
150
151
// Custom storage implementation
152
class MemoryCookieStorage : CookiesStorage {
153
private val cookies = mutableMapOf<String, MutableList<Cookie>>()
154
155
override suspend fun get(requestUrl: Url): List<Cookie> {
156
val host = requestUrl.host
157
return cookies[host]?.filter { cookie ->
158
// Apply cookie domain and path matching logic
159
cookieMatches(cookie, requestUrl)
160
} ?: emptyList()
161
}
162
163
override suspend fun addCookie(requestUrl: Url, cookie: Cookie) {
164
val host = requestUrl.host
165
cookies.getOrPut(host) { mutableListOf() }.add(cookie)
166
}
167
168
override fun close() {
169
cookies.clear()
170
}
171
}
172
173
val client3 = HttpClient {
174
install(HttpCookies) {
175
storage = MemoryCookieStorage()
176
}
177
}
178
```
179
180
### Cookie Access Functions
181
182
Functions for accessing cookies from HTTP client instances.
183
184
```kotlin { .api }
185
/**
186
* Get cookies for specific URL
187
*/
188
suspend fun HttpClient.cookies(url: Url): List<Cookie>
189
190
/**
191
* Get cookies for URL string
192
*/
193
suspend fun HttpClient.cookies(urlString: String): List<Cookie>
194
195
/**
196
* Get cookie by name from cookie list
197
*/
198
fun List<Cookie>.get(name: String): Cookie?
199
```
200
201
**Usage Examples:**
202
203
```kotlin
204
val client = HttpClient {
205
install(HttpCookies)
206
}
207
208
// Make request that sets cookies
209
client.get("https://api.example.com/login")
210
211
// Access cookies
212
val cookies = client.cookies("https://api.example.com")
213
println("Found ${cookies.size} cookies")
214
215
// Find specific cookie
216
val sessionCookie = cookies.get("JSESSIONID")
217
if (sessionCookie != null) {
218
println("Session ID: ${sessionCookie.value}")
219
println("Expires: ${sessionCookie.expires}")
220
println("Secure: ${sessionCookie.secure}")
221
println("HttpOnly: ${sessionCookie.httpOnly}")
222
}
223
224
// Access cookies by URL
225
val apiCookies = client.cookies(Url("https://api.example.com/data"))
226
val userCookie = apiCookies.get("user_id")
227
```
228
229
### Cookie Configuration
230
231
Advanced configuration options for cookie handling behavior.
232
233
```kotlin { .api }
234
/**
235
* Configure default cookies in HttpCookies plugin
236
*/
237
fun HttpCookies.Config.default(block: suspend CookiesStorage.() -> Unit)
238
```
239
240
**Usage Examples:**
241
242
```kotlin
243
val client = HttpClient {
244
install(HttpCookies) {
245
// Custom storage
246
storage = AcceptAllCookiesStorage()
247
248
// Add default cookies that will be sent with all requests
249
default {
250
// Authentication cookie
251
addCookie(
252
"https://api.example.com",
253
Cookie(
254
name = "auth_token",
255
value = "bearer_xyz123",
256
domain = "api.example.com",
257
path = "/",
258
secure = true,
259
httpOnly = true
260
)
261
)
262
263
// User preference cookies
264
addCookie(
265
"https://api.example.com",
266
Cookie(
267
name = "theme",
268
value = "dark",
269
maxAge = 30 * 24 * 3600 // 30 days
270
)
271
)
272
273
// Session tracking
274
addCookie(
275
"https://api.example.com",
276
Cookie(
277
name = "session_id",
278
value = generateSessionId(),
279
expires = GMTDate() + 3600_000 // 1 hour
280
)
281
)
282
}
283
}
284
}
285
```
286
287
### Cookie Attributes and Properties
288
289
Working with cookie attributes for security and behavior control.
290
291
```kotlin { .api }
292
/**
293
* Cookie class with all standard attributes
294
*/
295
data class Cookie(
296
val name: String,
297
val value: String,
298
val encoding: CookieEncoding = CookieEncoding.URI_ENCODING,
299
val maxAge: Int = 0,
300
val expires: GMTDate? = null,
301
val domain: String? = null,
302
val path: String? = null,
303
val secure: Boolean = false,
304
val httpOnly: Boolean = false,
305
val extensions: Map<String, String?> = emptyMap()
306
)
307
```
308
309
**Usage Examples:**
310
311
```kotlin
312
// Create cookies with various attributes
313
val basicCookie = Cookie("user", "john_doe")
314
315
val secureCookie = Cookie(
316
name = "auth_token",
317
value = "secure_token_123",
318
secure = true, // HTTPS only
319
httpOnly = true, // Not accessible via JavaScript
320
domain = "example.com",
321
path = "/api",
322
maxAge = 3600 // 1 hour
323
)
324
325
val sessionCookie = Cookie(
326
name = "session",
327
value = "session_abc",
328
expires = GMTDate() + 86400_000, // 24 hours from now
329
path = "/"
330
)
331
332
// Persistent cookie with long expiration
333
val persistentCookie = Cookie(
334
name = "remember_me",
335
value = "true",
336
maxAge = 30 * 24 * 3600, // 30 days
337
secure = true,
338
extensions = mapOf(
339
"SameSite" to "Strict"
340
)
341
)
342
343
// Add cookies to storage
344
val storage = AcceptAllCookiesStorage()
345
storage.addCookie("https://api.example.com", secureCookie)
346
storage.addCookie("https://api.example.com", sessionCookie)
347
storage.addCookie("https://api.example.com", persistentCookie)
348
```
349
350
### Manual Cookie Management
351
352
Manual cookie handling for advanced use cases.
353
354
```kotlin { .api }
355
/**
356
* Access cookie storage directly from client
357
*/
358
val HttpClient.cookies: HttpCookies?
359
get() = pluginOrNull(HttpCookies)
360
```
361
362
**Usage Examples:**
363
364
```kotlin
365
val client = HttpClient {
366
install(HttpCookies)
367
}
368
369
// Direct access to cookie plugin
370
val cookiePlugin = client.plugin(HttpCookies)
371
372
// Manual cookie management
373
val customCookies = listOf(
374
Cookie("custom1", "value1"),
375
Cookie("custom2", "value2")
376
)
377
378
// Add cookies manually before request
379
customCookies.forEach { cookie ->
380
cookiePlugin.storage.addCookie("https://api.example.com", cookie)
381
}
382
383
// Make request with manually added cookies
384
val response = client.get("https://api.example.com/data")
385
386
// Inspect response cookies
387
val responseCookies = response.setCookie()
388
responseCookies.forEach { cookie ->
389
println("Server set cookie: ${cookie.name} = ${cookie.value}")
390
}
391
```