【发布时间】:2016-09-14 13:41:43
【问题描述】:
服务器是用node.js/express写的,下面分享代码。
我的目标是在 ios 应用程序中验证用户身份,例如,假设用户看到了 UI
在 IOS/Swift 端,用户输入邮箱和密码
import UIKit
import Alamofire
class LoginViewController: UIViewController {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBAction func loginButton(sender: AnyObject) {
let parameters = [
"email": emailField.text!,
"password": passwordField.text!
]
// What exactly I have to write to authenticate the user??
Alamofire.request(.POST, "https://genietesting.herokuapp.com/auth/login", parameters: parameters, encoding: .JSON)
}
}
如果用户成功,则将根据服务器提供的令牌重定向到包含用户数据的新屏幕。
node.js/express 登录示例代码
app.post('/auth/login', function(req, res) {
User.findOne({ email: req.body.email }, '+password', function(err, user) {
if (!user) {
return res.status(401).send({ message: 'Invalid email and/or password' });
}
user.comparePassword(req.body.password, function(err, isMatch) {
if (!isMatch) {
return res.status(401).send({ message: 'Invalid email and/or password' });
}
res.send({ token: createJWT(user)});
});
});
});
上面的代码做的很简单,在mongodb数据库中查找用户,如果不存在,只需发送一个401附加消息,如果找到然后比较密码是否正确,如果正确是正确的然后将令牌发送回客户端。
我了解服务器部分,但在 IOS/Swift 部分,我必须写什么来使用服务器提供的令牌对用户进行身份验证?
【问题讨论】:
-
如果没有任何问题,您会将答案设置为已接受吗?
标签: ios node.js swift authentication alamofire