我有一个从web服务接收的HTTP cookie形式的身份验证令牌。目前,我依赖于iOS的默认行为,即将HTTP请求返回的cookies存储在NSHTTPCookieStorage对象中,该对象将cookies持久化,直到用户关闭应用程序。
但是,我希望在密钥链中的应用程序生命周期之间持久化cookie,这样当用户重新打开应用程序时,如果他们的cookie没有过期,他们将不需要再次登录。
在Swift中执行此操作的最简单方法是什么?我发现苹果编写的名为"KeychainItemWrapper“的代码,但它的文档相当参差不齐,似乎是为了存储用户的电子邮件(或用户名)和密码,而不是通用对象。有没有更简单的方法来使用密钥链,或者有更好的方法来安全地存储web服务的身份验证令牌?
发布于 2014-11-18 23:47:17
您应该检查SSKeychain:https://github.com/soffes/sskeychain。它在密钥链API上有一个非常好用的接口。
它本身不是Swift,但你应该仍然可以在swift应用程序中使用它。我不认为有一种方法可以存储对象本身,但正如您所提到的,您可以将cookie序列化为字符串并将其保存在密钥链中。
下面的例子说明了如何使用它。
NSString * const LoginService = @"com.example.loginService"; // unique identifier shared across your apps to identify various services your app may provide that require the keychain
NSString *cookie = // cookie string
NSString *userAccountIdentifier = // could be an email, username, id, or some other way to uniquely identify the user
[SSKeychain setPassword:cookie forService:LoginService account:userAccountIdentifier error:&error];发布于 2021-08-18 03:30:57
Swift 5+
我相信任何密钥链的第三个库都提供了Data存储方法(KeychainSwift,KeychainAccess)
缺少的部分是如何将[HTTPCookie]转换为Data,反之亦然。幸运的是,NSKeyedArchiver和NSKeyedUnarchiver提供了帮助。
下面是我在应用程序中使用的代码,用于通过keychain设置/获取cookie:
func setCookies(_ cookies: [HTTPCookie], for url: URL) {
guard let storeKey = storageKey(for: url) else { return }
do {
// Convert [HTTPCookie] to Data
let cookiesData = try NSKeyedArchiver.archivedData(withRootObject: cookies, requiringSecureCoding: false)
keychainStorage.set(value: cookiesData, forKey: storeKey)
} catch {
print("Fail to archive cookies to data: \(error)")
}
}
func getCookies(for url: URL) -> [HTTPCookie] {
guard let storeKey = storageKey(for: url),
let cookieData = keychainStorage.get(key: storeKey)
else { return [] }
do {
// Convert Data to [HTTPCookie]
let cookies = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(cookieData) as? [HTTPCookie]
return cookies ?? []
} catch {
print("Fail to unarchive data to cookies: \(error)")
return []
}
}
private func storageKey(for url: URL) -> String? {
guard let host = url.host else { return nil }
return "CookieStorage.\(host)"
}https://stackoverflow.com/questions/26997601
复制相似问题