已部署 + Swift 用户身份验证
Deployd + Swift User Authentication
我是 Swift 的新手。我想对用户进行身份验证。我正在使用 'Deployd' 作为我的服务器。 API 的文档是这样说的:
HTTP
To authenticate a user, send a POST request to /login with username
and password properties in the request body.
POST /users/login
{ "username": "johnsmith", "password": "password" }
我正在使用 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);
相反,您必须在请求中提供参数 body,因为规范规定它应该是您提供给服务器的参数。为此,请使用允许您包含参数的不同 Alamofire 方法:
let parameters = ("username" : user, "password" : password)
Alamofire.request(.POST, "http://localhost:2406/users/login", parameters: parameters)
并从调用中完全删除 .authentication :)
希望对您有所帮助!
我是 Swift 的新手。我想对用户进行身份验证。我正在使用 'Deployd' 作为我的服务器。 API 的文档是这样说的:
HTTP
To authenticate a user, send a POST request to /login with username and password properties in the request body.
POST /users/login
{ "username": "johnsmith", "password": "password" }
我正在使用 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);
相反,您必须在请求中提供参数 body,因为规范规定它应该是您提供给服务器的参数。为此,请使用允许您包含参数的不同 Alamofire 方法:
let parameters = ("username" : user, "password" : password)
Alamofire.request(.POST, "http://localhost:2406/users/login", parameters: parameters)
并从调用中完全删除 .authentication :)
希望对您有所帮助!