0

I'm stuck on an issue with cookies in a URLSession URLRequest. I have a Swift Playground where I add a cookie to my URLSession, and I expect to see it in the request to my local server, but it's not there. What am I missing? Here is my playground:

import Foundation
let config = URLSessionConfiguration.default
config.httpCookieStorage?.setCookie(
    HTTPCookie(properties: [
        HTTPCookiePropertyKey.domain: "http://localhost:8000",
        HTTPCookiePropertyKey.path: "/",
        HTTPCookiePropertyKey.name: "Eugene",
        HTTPCookiePropertyKey.value: "Test",
        HTTPCookiePropertyKey.secure: "TRUE",
        HTTPCookiePropertyKey.expires: Date(timeIntervalSinceNow: 1000000)
    ])!
)
config.httpShouldSetCookies = true
config.httpCookieAcceptPolicy = .always
let session = URLSession(configuration: config)
print(session.configuration.httpCookieStorage?.cookies)
var request = URLRequest(url: URL(string: "http://localhost:8000")!)
let task = session.dataTask(with: request) { data, urlResponse, error  in
    print(data)
    print(urlResponse)
    print(error)
}
task.resume()

This is the output of my playground:

Optional([<NSHTTPCookie
    version:0
    name:Eugene
    value:Test
    expiresDate:'2021-06-05 15:25:19 +0000'
    created:'2021-05-25 01:38:39 +0000'
    sessionOnly:FALSE
    domain:http://localhost:8000
    partition:none
    sameSite:none
    path:/
    isSecure:TRUE
 path:"/" isSecure:TRUE>])
Optional(1318 bytes)
Optional(<NSHTTPURLResponse: 0x6000005c5500> { URL: http://localhost:8000/ } { Status Code: 200, Headers {
    "Content-Length" =     (
        1318
    );
    "Content-Type" =     (
        "text/html; charset=utf-8"
    );
    Date =     (
        "Tue, 25 May 2021 01:38:40 GMT"
    );
    Server =     (
        "SimpleHTTP/0.6 Python/3.8.2"
    );
} })
nil

And this is the request the server sees, conspicuously missing the Cookie header:

127.0.0.1 - - [24/May/2021 20:38:40] "GET / HTTP/1.1" 200 -
ERROR:root:Host: localhost:8000
Accept: */*
Accept-Language: en-us
Connection: keep-alive
Accept-Encoding: gzip, deflate
User-Agent: URLSession/1 CFNetwork/1220.1 Darwin/20.3.0
Eugene
  • 3,417
  • 5
  • 25
  • 49

1 Answers1

0

One problem may be that Swift playgrounds at least historically didn't get along well with NSURLSession. This might be fixed now, in which case never mind, but if not, then you might try doing this in an actual app.

A second problem is that the isSecure property on the cookie is set, but you're trying to send the cookie over HTTP (not secure), so it won't ever get sent.

Finally, localhost itself may be problematic. See Cookies on localhost with explicit domain. I have no idea how Apple's cookie storage handles that edge case, but you should be aware of it anyway.

dgatwood
  • 10,129
  • 1
  • 28
  • 49