【问题标题】:oauth2.0 - token access request with password grant type with ios/swift 2 clientoauth2.0 - 带有密码授权类型的令牌访问请求,带有 ios/swift 2 客户端
【发布时间】:2016-01-22 07:17:10
【问题描述】:

我有自己的 web 应用程序,使用 laravel 作为后端,效果很好。

现在,我开始编写 IOS 应用程序(IOS 9、Xcode 7、Swift 2)并希望将其连接到我的网络应用程序数据库,以便使用 API 进行查询。

我卡住的第一步是关于用户通过 IOS 应用程序连接到 Web 应用程序数据库的登录名/密码。

我已在我的 Web 应用程序上安装了 oauth 2.0 配置并使用密码授予类型。用 Postman 测试,我可以使用带有 x-www-form-urlencoded 的正文中的以下参数获取访问令牌:

  • grant_type = 密码
  • client_id = f3d259ddd3ed8ff3843839b
  • client_secret = 4c7f6f8fa93d59c45502c0ae8c4a95b
  • 用户名 = user1@test.com
  • 密码 = 123456

现在,我想使用来自 IOS 应用的这些凭据访问此 Web 应用的数据库。

我在视图控制器中创建了一个登录表单。当我点击登录按钮时,我会启动一个 IBAction,如下所示:

    @IBAction func login(sender: UIButton){

    let myURL = NSURL(string: "http://myWebApplication.com/oauth/access_token")!
    let request = NSMutableURLRequest(URL: myURL)
    request.HTTPMethod = "POST"
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    let bodyStr:String = "grant_type=password&client_id=f3d259ddd3ed8ff3843839b&client_secret=4c7f6f8fa93d59c45502c0ae8c4a95b&username=user1@test.com&password=123456"
    request.HTTPBody = bodyStr.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        // Your completion handler code here
    }
    task.resume()


}

但什么也没发生。

你能告诉我哪里错了吗?

我花了几个小时寻找解决方案,上面的代码就是这个搜索的结果。不幸的是,还不够。

最重要的是,下一步要存储网络应用返回的访问令牌并使用它,以便我可以发送与该特定用户相关的查询?

提前感谢您的帮助

【问题讨论】:

    标签: oauth-2.0 swift2


    【解决方案1】:

    我遇到了同样的问题。主要来自 Cristina Moulton 的 iOS with REST APIs 一书,希望对您有所帮助。

    试试这个:# 使用 Alamofire 和 SwiftyJSON #

        func loginUser() {
    
        var code:String?
        var accessToken:String?
    
        let path:String = EndPoints.kRestEndpoint + EndPoints.kToken
    
        let parameters:[String:String] = ["grant_type": "password","client_id": "tes5@test.com.br", "client_secret": "123456"]
        let headers:[String:String] = ["Content-Type": "application/x-www-form-urlencoded","Accept": "application/json"]
    
        Alamofire.request(.POST, path, parameters: parameters, encoding: .URL, headers: headers).responseString { response in
    
          // Handle response to extract the OAuth Token
          if let error = response.result.error {
            print(error)
            return
          }
    
          // The access token + type
          print(response.result.value)
    
          if let receivedResults = response.result.value, jsonData = receivedResults.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
            let jsonResults = JSON(data: jsonData)
    
            for (key, value) in jsonResults {
              switch key {
              case "access_token":
                if let token = value.string {
                  code = token
                }
              case "token_type":
                if let type = value.string {
                  accessToken = "\(type) \(code!)"
                }
              case "expires_in":
                // Handle expiration
                print("It has expiration")
              default:
                print("got more than I expected from the OAuth token exchange")
                print(key)
              }
            }
            print("AccessToken: \(accessToken!)")
          } //End of receivedResults
    
          let defaults = NSUserDefaults.standardUserDefaults()
          defaults.setBool(true, forKey: "loadingOAuthToken")
        }
      }
    

    【讨论】:

      【解决方案2】:

      感谢弗雷德里科的帮助。

      我终于使用 KeychainWrapper 管理了这种方式(对于管理敏感信息的钥匙串非常有用)。

      如果有什么意见请告诉我:

          @IBAction func loginButtonTapped(sender: UIButton) {
          self.emailTextField.resignFirstResponder()
          self.passwordTextField.resignFirstResponder()
      
          if (self.emailTextField.text == "" || self.passwordTextField.text == "") {
              let alertView = UIAlertController(title: "Login failed",
              message: "Wrong username or password." as String, preferredStyle:.Alert)
              let okAction = UIAlertAction(title: "Try Again!", style: .Default, handler: nil)
              alertView.addAction(okAction)
              self.presentViewController(alertView, animated: true, completion: nil)
              return
          }
      
          // Check if the user entered an email
          if let actualUsername = self.emailTextField.text {
      
              // Check if the user entered a password
              if let actualPassword = self.passwordTextField.text {
      
                  // Build the body message to request the token to the web app
                  self.bodyStr = "grant_type=password&client_id=f3d259ddd3ed8ff3843839b&client_secret=4c7f6f8fa93d59c45502c0ae8c4a95b&username=" + actualUsername + "&password=" + actualPassword
      
                  // Setup the request
                  let myURL = NSURL(string: "http://test.com/oauth/access_token")!
                  let request = NSMutableURLRequest(URL: myURL)
                  request.HTTPMethod = "POST"
                  request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
                  request.setValue("application/json", forHTTPHeaderField: "Accept")
                  request.HTTPBody = bodyStr.dataUsingEncoding(NSUTF8StringEncoding)!
      
                  let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                      (data, response, error) -> Void in
                      if let unwrappedData = data {
      
                          do {
      
                              // Convert the Json object to an array of dictionaries
                              let tokenDictionary:NSDictionary = try NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
      
                              // Get the token
                              let token:String = tokenDictionary["access_token"] as! String
      
                              // Keep record of the token
                              let saveToken:Bool = KeychainWrapper.setString(token, forKey: "access_token")
      
                              // Dismiss login view and go to the home view controller
                              self.dismissViewControllerAnimated(true, completion: nil)
      
                          }
                          catch {
                              // Wrong credentials
                              // Reset the text fields
                              self.emailTextField.text = ""
                              self.passwordTextField.text = ""
      
                              // Setup the alert
                              let alertView = UIAlertController(title: "Login failed",
                                  message: "Wrong username or password." as String, preferredStyle:.Alert)
                              let okAction = UIAlertAction(title: "Try Again!", style: .Default, handler: nil)
                              alertView.addAction(okAction)
                              self.presentViewController(alertView, animated: true, completion: nil)
                              return
                          }
                      }
                  }
                  task.resume()
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-28
        • 2015-11-03
        • 2020-01-10
        • 1970-01-01
        • 2022-08-18
        • 2020-02-25
        相关资源
        最近更新 更多