Search code examples
iosobjective-ckeychainitemwrapper

Storing access token and refresh token in KeyChain


I would like to know how to effectively store the access token, refresh tokens and their expirations in the iOS keychain.

All the examples I have seen seem to store only one key-value combination. How do we store multiple key values for one keychain identifier?

If there is a better way to store the above, please let me know.


Solution

  • You will first want to build a NSDictionary with the key/values you want. Next, you could use something like Lockbox to store that NSDictionary to the keychain, using the provided setDictionary:forKey: interface.

    UPDATE: To change values stored in that dictionary, you only have to pass by a NSMutableDictionary (that's the common way of doing):

    NSMutableDictionary *mutableDict = [[LockBox dictionaryForKey:@"YourRefreshTokenDictionaryKey"] mutableCopy];
    mutableDict[@"access_token"] = @"NewAccessToken";
    [LockBox setDictionary:mutableDict forKey:@"YourRefreshTokenDictionaryKey"]; 
    

    FYI, a NSMutableDictionary is a subclass of NSDictionary, so it's safe to save that back directly to the keychain!