I will get thousands of user's tokens when they authorise to us via OAuth (external provider).

I am trying to find out what the best practices to securely encrypt user's token into a database.

I am considering using libsodium (Halite in PHP) to encrypt the token and then save into MySQL. Encryption key is stored in the .env file. But what if web server got hacked and they could manage access to .env?

Second option is use Vault (HashiCorp) which is installed on the separate server. The web server would have to access to Vault using API.

Which one do you think is more secure?

1 Answer 1


There are couple of ways to do this, depending on if the webserver really needs read/write access to the oauth tokens.

I've been using Vault for a while now, and I think this would be the way to go. You can use something like the approle auth backend (vault auth-enable approle) to let your servers write the tokens based on different policies (so they are limited to only writing those tokens).

Since the webserver can only write, you need something that can read the oauth data, and I suggest you have a some queue tool here, with workers that can read and processes whatever you need to do, and preferably not on the webserver (so that read/write access is split on different machines). The worker could use a read/write or read only app-role.

Which secret backend you use for your data storage (consul/file/DB) doesn't matter. Choose what you are comfortable with (I like consul since it's resilient and not depending on mysql or other DB replication), but whatever you choose, vault will ensure that the data is encrypted before it's written.

If the webserver is hacked, well, then it could cannot read the tokens, so the data should be pretty safe (as long as you protect machine/vault/worker communication).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .