URLSession没有获取SessionID Cookie

时间:2019-06-08 14:10:45

标签: swift

如何在成功登录POST后获取所有cookie?我有以下代码登录到我的Django服务器,但是似乎从来没有创建session_id cookie,只有一个csrftoken cookie。目前,我是从HTTPCookieStorage.shared.cookies获取它们的,但是我感觉需要手动从URLSession.dataTask中提取它们?

登录:

func login() {
        let url = urlForEP(ep: loginEP)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue(self.csrfToken, forHTTPHeaderField: "X-CSRFToken")
        let postData = [
            "username" : username,
            "password" : password
        ]
        let jsonData = try! JSONSerialization.data(withJSONObject: postData, options: [])
        let task = session.uploadTask(with: request, from: jsonData) { data, response, error in

            guard (response as! HTTPURLResponse).statusCode == 200 else {
                print("Failed to login")
                return
            }

            print("Successfully logged in!")
            self.printCookies()

            self.getItems()

        }
        task.resume()
    }

Cookie打印输出:

func printCookies() {
        for cookie in HTTPCookieStorage.shared.cookies! {
            print("\(cookie.name): \(cookie.value)")
        }
    }

结果:

csrftoken: lLgwYilYyqGzBfmkyvn8rZz6t6j8C8Ly7gwFxkcgAst1AODGukBCY6PGTXmTflmz

0 个答案:

没有答案