oauth2.0-使用ios/swift 2客户端具有密码授予类型的令牌访问请求 [英] oauth2.0 - token access request with password grant type with ios/swift 2 client
问题描述
我有自己的使用laravel作为后端的Web应用程序,效果很好.
I have my own web application using laravel as back-end which works fine.
现在,我开始对IOS应用(IOS 9,Xcode 7,Swift 2)进行编码,并希望将其连接到我的Web应用数据库,以便可以使用API进行查询.
Now, I'm starting coding the IOS app (IOS 9, Xcode 7, Swift 2) and would like to connect it to my web app database so I can use API for queries.
我遇到的第一步是用户通过IOS应用程序连接到Web应用程序数据库的登录名/密码.
My first step which I'm stuck is about the login/password for the user to connect to the web app database through the IOS app.
我已在Web应用程序上安装了oauth 2.0配置,并使用了密码授予类型.经过Postman的测试,我可以使用x-www-form-urlencoded在正文中使用以下参数来获取访问令牌:
I have installed an oauth 2.0 configuration on my web app and using the password grant type. Tested with Postman and I can get the access token using the following parameter in the body with x-www-form-urlencoded:
- grant_type =密码
- client_id = f3d259ddd3ed8ff3843839b
- client_secret = 4c7f6f8fa93d59c45502c0ae8c4a95b
- 用户名= user1@test.com
- 密码= 123456
现在,我想使用IOS应用程序中的这些凭据来访问此Web应用程序的数据库.
Now, I want to access to the database of this web app with these credentials from the IOS app.
我已经在视图控制器中创建了一个登录表单.当我点击登录按钮时,我将按以下方式启动IBAction:
I have created a login form in the view controller. When I tap the login button, I launch an IBAction as follow:
@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()
}
但是什么也没发生.
你能告诉我我哪里错了吗?
Could you please tell me where I'm wrong?
我花了几个小时来寻找解决方案,上面的代码是这次搜索的结果.不幸的是,这还不够.
I spent hours searching for solution and the code above is the result of this search. Unfortunately, not sufficient.
最重要的是,下一步要存储该Web应用程序将返回并使用的访问令牌,以便我可以发送与此特定用户相关的查询吗?
On top of that, what is the next step to store the access token that the web app will return and use it so I can send queries related to this particular user?
预先感谢您的帮助
推荐答案
感谢Frederico的帮助.
Thank you Frederico for your help.
我最终使用KeychainWrapper(对管理敏感信息的钥匙串非常有用)进行这种管理.
I finally managed this way using KeychainWrapper (very useful to manage keychain for sensitive information).
让我知道是否有任何评论:
Let me know if anything comment:
@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()
}
}
}
这篇关于oauth2.0-使用ios/swift 2客户端具有密码授予类型的令牌访问请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!