【问题标题】:Deployd + Swift User Authentication已部署 + Swift 用户身份验证
【发布时间】:2015-10-29 16:05:05
【问题描述】:

我是 Swift 新手。我想对用户进行身份验证。我正在使用“已部署”作为我的服务器。 API 的文档是这样说的:

HTTP

要对用户进行身份验证,请使用用户名向 /login 发送 POST 请求 和请求正文中的密码属性。

POST /users/login

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

我正在使用 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; } })

我知道我这样做的方式完全错误。

【问题讨论】:

    标签: ios swift alamofire deployd


    【解决方案1】:

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

    相反,您必须在请求正文中提供参数,因为规范说它应该是您提供给服务器的内容。为此,请使用允许您包含参数的不同 Alamofire 方法:

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

    并从通话中完全删除 .authentication :)

    希望对你有帮助!

    【讨论】:

    • 不用担心,很高兴为您提供帮助 :) 享受吧!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多