【问题标题】:How do i do token based authentication with Alamofire?如何使用 Alamofire 进行基于令牌的身份验证?
【发布时间】: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


【解决方案1】:

基本上你应该检查服务器为你的请求提供的响应。我认为以下代码会有所帮助:

Alamofire.request(.POST, "https://genietesting.herokuapp.com/auth/login", parameters: parameters, encoding: .JSON)
    .responseString { response in
         print("Success: \(response.result.isSuccess)")
         print("Response String: \(response.result.value)")
         if let httpError = response.result.error {
             let statusCode = httpError.code
             // show the error message to user
         } else { //no errors
             let statusCode = (response.response?.statusCode)!
             // proceed to the next page
         }
}

【讨论】:

  • 我需要将令牌存储在 IOS 部分的钥匙串或 nsuserdefaults 中吗?
  • 这真的取决于你以后需要什么令牌。如果您希望用户每次打开应用程序时都登录,您可以将其存储在内存中,但如果您想保留它以备将来使用,出于安全原因,我建议将其保留在钥匙串中,而不是用户默认值。
  • 存储在内存中?和其他数据库一样,比如 redis 或 mongodb?
  • 不!我的意思是在 RAM 中的一个变量中。
猜你喜欢
  • 1970-01-01
  • 2016-08-24
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
  • 2020-04-13
  • 1970-01-01
  • 2021-01-25
相关资源
最近更新 更多