How to secure jwt tokens

Whether you’re building your own custom backend, integrating with Firebase, or authenticating through Facebook at some point your app may need to save a security token somewhere.

NSUserDefaults is the wrong way. The Security Framework has got you covered.

TL;DR: Token.swift

The keychain is different from NSUserDefaults. The data is encrypted by iOS, and the information can’t be read by other apps. Retrieving data from the keychain is done using a query interface.

For example:

1
2
3
4
5
var query = [String: Any]()
query[kSecClass as String] = kSecClassInternetPassword
query[kSecAttrAccount as String] = "com.app.foo.bar.token"
query[kSecAttrServer as String] = "my.apps.backend.com"
query[kSecValueData as String] = "<token-data>".data(using: .utf8)

Followed by a call to one of these functions

examples:

1
2
3
SecItemDelete(query as CFDictionary)
SecItemAdd(query as CFDictionary, nil)
SecItemCopyMatching(query as CFDictionary, &item)

last update time 2018-09-01