I have an authentication token received from a web service in the form of an HTTP cookie. Currently I am relying on iOS's default behavior of storing cookies returned from HTTP requests in the NSHTTPCookieStorage
object which persists the cookies until the user closes the application.
However, I would like to persist the cookie between application lifecycles in the keychain so that when the user reopens the application, if their cookie is not expired, they will not need to login again. It does not seem there is an easy way to store generic objects into the keychain, so it seems the best route is to serialize the dictionary object retrieved via NSHTTPCookie
's property
to a string and store that in the keychain. I can then rebuild the cookie via initWithProperties
constructor in NSHTTPCookie
and stick it back in the NSHTTPCookieStorage
object.
What is the easiest way to do this in Swift? I found code Apple wrote called "KeychainItemWrapper", but the documentation for it is pretty spotty and it seems that it was made for storing user's emails (or usernames) and passwords, more than generic objects. Is there an easier way to work with the keychain, or a better way to safely store the web service's authentication token?
You should checkout SSKeychain: https://github.com/soffes/sskeychain. It has a really nice and usable interface over the keychain API's.
It's not Swift per se, but you should still be able to use it in a swift app. I don't think there's a way to store objects themselves, but as you mentioned you can serialize the cookie into a string and save it in the keychain.
Example below for how it could be used.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With