Search code examples
iosswiftalamofire

Alamofire POST with Authorization


I have a problem with one request POST in ios using swift ...

In curl i send one request like this:

curl -H "Authorization: token ce2800d53d520b4a73a005a611d53d299e0c1d5e"....

and me server response with 200

However en ios i make me request like this:

let parameters = [
    "date_of_birth": strDate!,
    "address": strPlace!,
]

let parametersH = [
    "Authorization": "token 9640e65f66429415fb9359739ed8bc3f57cb0566"
]


Alamofire.request(Alamofire.Method.POST, "http://192.168.1.70:8000/profileMe/", parameters: parameters,headers:parametersH).progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
    }.responseJSON{ request, response, JSON, error in

        if (error == nil) {
            println(response)
        }
        else{
            println(error)
        }

    }

And me server send one 403....

How i can make me request with one valid authentication?....

I dont know ... because the header is incorrect ...when i send the request...

When i send this request en android i dont have problem.....and the request is similar...


Solution

  • I ran into this same problem and have been debugging for an entire day and finally figured it out. I'm almost positive the OP was using Django.

    It's a subtlety with either Alamofire or the underlying Swift/Objective C networking code. I think if Alamofire receives a Set-Cookie in a response header, that it will send this information as a Cookie payload in subsequent request headers. This is different behaviour than other HTTP networking libraries.

    As it pertains to Django, Alamofire will send the sessionid cookie value under the hood on subsequent requests, which makes Django think a session has been started and then you haven't provided the correct CSRF tokens when using SessionAuthentication and it'll throw a 403 permissions error. That's why you can successfully perform the request the first time and then it throws a 403 the second time.

    To get around this problem, and in general to stop Alamofire from auto sending cookie values, set

    let headers = [
        "Cookie": ""
    ]