Best Practice to Store a Bearer Token

Hey RW Crew!

I’ve just started interacting with third-party APIs and connect to APIs using a bearer token.

Currently, I just submit the token as a string in the source code but I suspect that’s not the best practice.

What is the best practice protocol to store a bearer token for an app if I must retrieve the token manually? In other words, I can’t request a token in app.

Do I store this token in a txt file on my hard drive and read it in? How do I go about protecting the token when I use a github repository?

Any suggestions will be helpful. Thanks for considering my question :slight_smile:

A Token is a type of secret. iOS/macOS solve that very well with the Keychain. Here’s a good read on that by @lorenzoboaro :

I made changes to the library above and produced:

It needs some updates, but it’s a good reference.

Hi Robert,

Thanks for suggesting something further to research. I didn’t realise it would be so complicated.

While not as secure as Keychain, would storing the key on a file locally and reading in that file at compile time be a more convenient/less secure approach that would fit sample apps?

With the right library, Keychain is much simpler than operating a file, where you have to deal with other things such as Sandbox permissions, file location, etc. Not a big deal, but something to consider.

Let’s say you use the following library:

This will save:

let keychain = Keychain(service: "com.example.github-token")
keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef"

This will fetch:

let token = keychain["kishikawakatsumi"]

I’d give that a try.