使用Alamofire POST数据时CSRF失败

时间:2016-03-11 13:14:38

标签: django-rest-framework alamofire

我使用django-reat-framework作为后端并使用SessionAuthentication和TokenAuthentication。 当我使用httpie发送请求时,这很有效。

http POST http://127.0.0.1:8000/api/users/ email="abc@abc.com" user_name="abc" passwod="1234"

但是当我使用Alamofire时

Alamofire.request(.POST, "http://127.0.0.1:8000/api/users/", parameters: ["email": emailField.text!, "user_name": usernameField.text!, "password": passwordField.text!], encoding: .URL )
            .responseJSON { response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
        }

返回此

Optional(<NSMutableURLRequest: 0x7fe24e15d640> { URL: http://127.0.0.1:8000/api/users/ })
Optional(<NSHTTPURLResponse: 0x7fe24bf3a080> { URL: http://127.0.0.1:8000/api/users/ } { status code: 403, headers {
    Allow = "GET, POST, HEAD, OPTIONS";
    "Content-Type" = "application/json";
    Date = "Fri, 11 Mar 2016 13:09:59 GMT";
    Server = "WSGIServer/0.2 CPython/3.4.3";
    Vary = "Accept, Cookie";
    "X-Frame-Options" = SAMEORIGIN;
} })
Optional(<7b226465 7461696c 223a2243 53524620 4661696c 65643a20 43535246 20746f6b 656e206d 69737369 6e67206f 7220696e 636f7272 6563742e 227d>)
SUCCESS
JSON: {
    detail = "CSRF Failed: CSRF token missing or incorrect.";
}

但是127.0.0.1:8000/api/users/不需要任何权限,当我使用httpie.So时我没有发送csrf令牌,这里有什么问题?

3 个答案:

答案 0 :(得分:2)

这个标题对我有用:

let headers = [
   "Cookie": ""
]


Alamofire.request(urlString, method: .post, parameters: ["username": username!, "password": password!],encoding: JSONEncoding.default, headers: headers).responseJSON {
    response in
    switch response.result {
           case .success:
                print(response)                    
                break
            case .failure(let error):
                print(error)
    }

}

从这里开始:{{3}}

答案 1 :(得分:1)

对使用Django创建的API的POST / DELETE请求需要与请求一起传递有效的csrftoken。

您需要在进行任何POST调用之前生成令牌。要生成令牌,请参阅 https://docs.djangoproject.com/en/1.9/ref/csrf/

在从cookie获取csrftoken值之后,在请求的标头中传递令牌

        let headers = [ "Accept":"application/json" ,  "Content-Type": "application/json" , "X-CSRFToken" : csrftoken]


        Alamofire.request(.POST, "http://127.0.0.1:8000/api/users/", headers: headers, parameters: params, encoding:  .JSON)
            .validate()
            .responseJSON { response in

                switch response.result {
                case .Success(let responseContent):

答案 2 :(得分:0)

在相应的API视图中从 authentication_classes 中取消 SessionAuthentication 。它会&#34;禁用&#34;此视图的Cookie,表示 CSRF-token不再需要