user27353519
user27353519

Reputation: 1

When to fetch Auth Token from Swift Keychain? At application startup or during each request to backend?

I store an authorization key in keychain, which is required to use a backend API. Is it good practice to get this authorization key at application startup and keep it in a variable, or should I query the keychain before every request to the backend?

I wonder if retrieving the key from keychain on every request will not negatively affect performance and cause errors that randomly happen when retrieving data from keychain.

Upvotes: 0

Views: 59

Answers (1)

Pincha
Pincha

Reputation: 156

Retrieving the key from the keychain once at startup and storing it in memory reduces the overhead of accessing the keychain on every request and simplifies the code as you only need to fetch the key once and then use the in-memory variable throughout the application's lifecycle.

But on the other hand, storing the key in memory for an extended period can be a security risk, especially if the app remains running in the background or if there is a possibility of memory dumping attacks.

Other thing to take into consideration is the lifetime of that authorization key, since you may need to update the cached value.

Query the keychain before every request ensures that the key is only in memory for the shortest time possible, reducing the window for potential attacks.

Although keychain access is slower than memory access, the performance hit is generally minimal unless you are making a very large number of requests in a short period.

So i'm in favor of fetching from keychain when needed because all the projects i worked on, the security is a must and the performance impact is nothing that will have a big impact, but it all depends on your specific needs.

Upvotes: 0

Related Questions