我用Swift 4编写了一个使用Discogs API的应用程序。因此,我要求用户能够访问Discogs帐户上的个人数据,因此我使用OAuthSwift对他们的API进行身份验证。目前,我能够启动auth流,登录并返回an oauthToken和oauthTokenSecret。
向他们的https://api.discogs.com/oauth/identity发出随后的请求,我会被返回一个用户对象,所以我很高兴现在我可以登录并发出经过身份验证的请求。
但是,我不明白当应用程序第一次启动时,我如何检查用户是否经过身份验证。目前,我没有存储响应,而是在嵌套回调中调用标识端点。
import UIKit
import OAuthSwift
class ViewController: UIViewController {
let oauthSwift = OAuth1Swift(
consumerKey: "foo",
consumerSecret: "bar",
requestTokenUrl: "https://api.discogs.com/oauth/request_token",
authorizeUrl: "https://www.discogs.com/oauth/authorize",
accessTokenUrl: "https://api.discogs.com/oauth/access_token"
)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = .white
kickOffAuthFlow()
}
fileprivate func kickOffAuthFlow() {
oauthSwift.authorizeURLHandler = SafariURLHandler(viewController: self, oauthSwift: oauthSwift)
guard let callbackURL = URL(string: "foo.bar.boobaz:/oauth_callback") else { return }
oauthSwift.authorize(withCallbackURL: callbackURL, success: { (credential, response, parameters) in
_ = self.oauthSwift.client.get("https://api.discogs.com/oauth/identity", success: { (response) in
guard let dataString = response.string else { return }
print(dataString)
}, failure: { (error) in
print("error")
})
}) { (error) in
print(error.localizedDescription)
}
}
}这种情况下的最佳实践是什么?如何存储这些令牌,以及如何确保一旦用户登录,它们就不会被迫在下一次打开应用程序时登录(如果令牌尚未过期,但这是我准备在以后处理的另一个问题)。
来自web开发背景,我只需将令牌存储在会话存储中,在加载时,我将检查令牌上的exp,并请求一个新的令牌或采取其他一些操作。
我还没有完全理解这在iOS开发中的工作原理。
发布于 2018-01-14 10:55:04
您有两个选项可以将访问令牌存储在本地。
1. UserDefault
使用UserDefault将令牌存储在内存中。当应用程序启动时,检查令牌是否存储在userdafault中。UserDefault用作短内存存储,您可以在其中存储小数据。如果你杀了这个应用程序,它就会留在记忆中。
let tokenIdentifier = "TokenIdentifier"
func storeAccessToken(token: String) {
UserDefaults.standard.set(token, forKey: tokenIdentifier)
}
func checkUserLogin() {
if UserDefaults.standard.value(forKey: tokenIdentifier) != nil {
print("User is Login")
}
else {
print("User need to login")
}
}请查看此以了解有关用户默认值的更多信息。
https://swift3tutorials.com/swift-3-user-defaults/
https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults
2.密钥链
Userdefault不安全。访问令牌是一个敏感的信息,应该存储在一个安全的地方。因此,将访问令牌存储在用户默认值中并不是正确的选择。必须将访问令牌存储在密钥链中。使用SwiftKeychainWrapper pod将令牌存储在密钥链中。
let tokenIdentifier = "TokenIdentifier"
func storeAccessToken(token: String) {
KeychainWrapper.standard.set(token, forKey: tokenIdentifier)
}
func checkUserLogin() {
let token: String? = KeychainWrapper.standard.string(forKey: tokenIdentifier)
if token != nil {
print("User is Login")
}
else {
print("User need to login")
}
}https://stackoverflow.com/questions/48248575
复制相似问题