Securely storing an access token

2019-04-04 17:55发布

问题:

What security measures should I put in place to ensure that, were my database to be compromised, long-life access tokens could not be stolen?

A long-life access token is as good as a username and password for a particular service, but from talking to others it seems most (myself included) store access tokens in plain text. This seems to be to be just as bad as storing a password in plain text. Obviously one cannot salt & hash the token.

Ideally I'd want to encrypt them, but I'm unsure of the best way to do this, especially on an open source project.

I imagine the answer to this question is similar to one on storing payment info and PCI compliance, but I'd also ask why there isn't more discussion of this? Perhaps I'm missing something.

回答1:

Do you just want to verify a token provided by others? If so, treat it as you would a password. Use a byte derivation algorithm like Password Based Key Derivation Function 2 (PBKDF2) (also described in RFC 2898) with 10,000 iterations and store the first 20 bytes or so. When the token is received. It is not practically reversible.

Do you want to present the token to others for authentication? If so, this is a challenge because, if your application can decrypt or otherwise get access to the token, so can an attacker. Think Shannon's Maxim, the attacker knows the system, especially for an open source project.

In this case, the best approach is to encrypt the tokens with a strong algorithm (e.g. AES256), generate keys using a strong cryptographic standard random number generator and store the key(s) securely in a different location to the data, such as in a permission protected file outside the database in the example above. The latter means that SQL injection attacks will not reveal the keys.