Search code examples
swiftpostcookieshttprequestalamofire

Automatically Update Cookies From HTTP Post Request With Multiple Redirects In Swift


I am trying to create a login API from scraped website data (I have gotten permission to do so). Currently the login of the website executes a POST request with multiple redirects. At each redirect it seems that response cookies always contain a new SET-COOKIE accompanied by some value, i.e. a session ID.

I have been able to get the request to go through perfectly on the website Hurtl.it and through programs such as Postman and Paw, but I cannot get the request to complete properly via Alamofire or NSURLSession unless I explicitly enter the cookies returned from Postman or Paw that contain the session ID among other cookies that are set during the redirects.

I'm wondering if there is anyway that I can set the cookies to automatically update and send the updated cookies during the redirects in Swift.

This is the Alamofire code currently being used that returns the proper output but only for the session ID/cookie that is entered so even if I change the username/password it still outputs the results as if they had never need changed:

func sendRequestRequest() {

    // Add Headers
    let headers = [
        "Cookie":"Cookie string taken explicitly from Paw or Postman",
        "Content-Type":"application/x-www-form-urlencoded",
        ]

    // Form URL-Encoded Body
    let body = [
        "inputEnterpriseId":"username",
        "password":"password",
        "queryString":"null",
        "BTN_LOGIN":"Login",
        ]

    // Fetch Request
    Alamofire.request(.POST, "url", headers: headers, parameters: body, encoding: .URL)
        .validate(statusCode: 200..<300)
        .responseString { response in
            if (response.result.error == nil) {
                debugPrint("HTTP Response Body: \(response.result.value)")
            }
            else {
                debugPrint("HTTP Request failed: \(response.result.error)")
            }
    }
}

Please let me know if anyone needs more information. Thank you so much for any help!


Solution

  • I figured out the answer, but ended up using NSURLSession to do it. The piece that fixed my cookie issue is:

                if let httpResponse = response as? NSHTTPURLResponse, let fields = httpResponse.allHeaderFields as? [String : String] {
                let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(fields, forURL: response!.URL!)
                NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies, forURL: response!.URL!, mainDocumentURL: nil)
                for cookie in cookies {
                    var cookieProperties = [String: AnyObject]()
                    cookieProperties[NSHTTPCookieName] = cookie.name
                    cookieProperties[NSHTTPCookieValue] = cookie.value
                    cookieProperties[NSHTTPCookieDomain] = cookie.domain
                    cookieProperties[NSHTTPCookiePath] = cookie.path
                    cookieProperties[NSHTTPCookieVersion] = NSNumber(integer: cookie.version)
                    cookieProperties[NSHTTPCookieExpires] = NSDate().dateByAddingTimeInterval(31536000)
    
                    let newCookie = NSHTTPCookie(properties: cookieProperties)
                    NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(newCookie!)
    
                    print("name: \(cookie.name) value: \(cookie.value)")
                }