使用Alamofire在Swift中进行摘要式身份验证

时间:2014-09-17 16:57:59

标签: swift digest-authentication alamofire

我更改了Alamofire示例代码以尝试支持摘要式身份验证,但无法使其正常工作。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let detailViewController = segue.destinationViewController.topViewController as? DetailViewController {
        func requestForSegue(segue: UIStoryboardSegue) -> Request? {
            switch segue.identifier {
                case "GET":
                    let user = "Administrator"
                    let password = "password"

                    let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
                    let protectionSpace = NSURLProtectionSpace(host: "172.16.0.56", port: 443, `protocol`: "https", realm: "myrealm", authenticationMethod: NSURLAuthenticationMethodHTTPDigest)
                    return Alamofire.request(.GET, "https://172.16.0.56")
                        .authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
                        .response {(request, response, _, error) in
                            println(response)
                }
                default:
                    return nil
            }
        }

        if let request = requestForSegue(segue) {
            detailViewController.request = request
        }
    }
}

如果我运行此代码,那么我得到以下响应:

Optional(<NSHTTPURLResponse: 0x7fa0c3525320> { URL: https://172.16.0.56/ } { status code: 401, headers {
"Accept-Ranges" = bytes;
"Cache-Control" = "no-cache";
Connection = "keep-alive";
"Content-Length" = 163;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Wed, 17 Sep 2014 16:45:29 GMT";
Expires = 0;
Server = "MyServer";
"Www-Authenticate" = "Digest realm=\"myrealm\", nonce=\"4642875290551863156110287\", algorithm=\"MD5\", qop=\"auth\", stale=\"FALSE\"";
} })

似乎Alamofire没有尝试将用户名和密码发送回服务器,并且返回了nonce,我只是从服务器返回'Not Authorized'页面。 Alamofire是应该代表我进行摘要式身份验证还是我需要编写更多代码?

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

这对我有用:

  let userNameValue = "user"
    let passwordValue = "passwd"
    let credential = URLCredential(user: userNameValue, password: passwordValue, persistence: .forSession)
    let sessionMananager = Alamofire.SessionManager.default
    _ = sessionMananager.request("http://httpbin.org/basic-auth/\(userNameValue)/\(passwordValue)")
        .authenticate(usingCredential: credential)
        .responseJSON { response in
            print("Response: \(String(describing: response.response))")
            print("Result: \(response.result)")

            let json = JSON(response.result.value!)
            print("this is jsn: \(json)")
    }
}