io9 - Alamofire令牌请求失败,401 debug errorsite curl来自debugPrint工作

时间:2016-04-11 21:20:07

标签: ios django oauth-2.0 alamofire django-authentication

我的问题是在Previous question之前提出过的问题。

我正在使用Alamofire 3.2.1,XCode 7.3,iOS9。

这是我的代码,旨在从django oauth工具包实现的OAuth服务器(localhost)中获取令牌:

let params = ["grant_type": "password",
                  "username": "rosa",
                  "password": "rosa1234"]

    let request = Alamofire.request(.POST, url, parameters: params).authenticate(user: __clientID, password: __clientSecret)

    debugPrint(request)

    request.validate(statusCode: 200..<300)
        .validate(contentType: ["application/json"])
        .responseSwiftyJSON({ (request, response, json, error) in
            debugPrint(response)

            if (error != nil) {
                print(error.debugDescription)
                return completionHandler(token: nil, error: error)
            }

            // call the completionHandler function (object) to deal with data further
            return completionHandler(token: json.string, error: nil)
        })

请求的调试打印提供了一个有效的curl命令,它可以在命令行上运行:

curl -i \
-X POST \
-u PrtRUN9ra7LHCYWbiReaAjO9I26lJhLhRSAUJgtr:kTvxqKmClDAL3tbdyZdyBZgsfsfXtagMpZyFjSZwpIknxM43l6ZIvJxJGXu2J2FuHf4JMLfopDoAzkF6vHSRq4GZkbnEZSmmUnMvkhMvSucbhWUdzCpxuj9qtc8beaQ3 \
-H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \
-H "User-Agent: IntelliCafe/xsoft.IntelliCafe (1; OS Version 9.3 (Build 13E230))" \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
-H "Accept-Language: en-US;q=1.0" \
-d "grant_type=password&password=rosa1234&username=rosa" \
"http://localhost:8000/o/token/"

但代码在我的应用中不起作用。错误是401:

    Optional(<NSHTTPURLResponse: 0x7d183950> { URL: http://localhost:8000/o/token/ } { status code: 401, headers {
    "Cache-Control" = "no-store";
    "Content-Type" = "application/json";
    Date = "Mon, 11 Apr 2016 20:43:48 GMT";
    Pragma = "no-cache";
    Server = "WSGIServer/0.1 Python/2.7.10";
    "X-Frame-Options" = SAMEORIGIN;} }) 
Optional(Error Domain=com.alamofire.error Code=-6003 "Response status code was unacceptable: 401" UserInfo={NSLocalizedFailureReason=Response status code was unacceptable: 401})

这个问题让我抓狂。任何帮助都将不胜感激!

提前致谢。

1 个答案:

答案 0 :(得分:0)

我写了一个django rest视图来打印出请求的元数据,发现clientID和clientSecret没有被django服务器实现正确嵌入/处理。

使用Alamofire文档中显示的Authorization标头。