部署+ Swift用户认证



我是Swift的新手。我想验证一个用户。我使用"部署"作为我的服务器。这是API的文档所说的:

HTTP

要验证用户,发送POST请求到/login with username和请求体中的密码属性。

POST/用户/登录

{"用户名":"那","密码":"密码"}

我使用Alamofire来解析JSON数据。下面是我的代码:

        let user = "root"
        let password = "root"
        // this is a testing user i've created in deployd's dashboard.
        let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
        Alamofire.request(.POST, "http://localhost:2406/users/login/(user)/(password)")
            .authenticate(usingCredential: credential)
            .response { request, response, _, error in
                println(response)
        }

这是Xcode控制台的响应:

Optional(<NSHTTPURLResponse: 0x7fdd906dc3a0> { URL: http://localhost:2406/users/login/root/root } { status code: 400, headers {
    Connection = "keep-alive";
    "Content-Type" = "application/json";
    Date = "Thu, 06 Aug 2015 13:01:54 GMT";
    "Transfer-Encoding" = Identity; } })

我知道我做这件事的方式完全不对。

您正在使用http身份验证(headers),但服务器/api并没有要求您这样做(它实际上说400 -错误请求-因此应该指出错误使用api);

相反,您必须在请求体中提供参数,因为规范规定它应该是您提供给服务器的。要做到这一点,请使用Alamofire的不同方法,该方法允许您包含参数:

let parameters = ("username" : user, "password" : password)
Alamofire.request(.POST, "http://localhost:2406/users/login", parameters: parameters)

并从调用中删除。authentication:)

希望有帮助!

最新更新