What to use to generate OAuth 2 access token

2019-05-31 16:49发布

问题:

So I am playing around with trying to implement as closely as I can OAuth 2 for this API I am building. I am at the point where I need to generate the access_token however I am trying to figure out the best method of doing this. I have read in a very place where people are encrypting the revenant information and the access_token (like expired date, client id, etc...) in order to prevent a database lookup on each API call.

I was think about that and thought, how does that way of generating the access_token handle revoking access? I mean one of the advantages of using OAuth is the ability to revoke access to your data for an application if I am just using the encrypted data without a look up in the database, if I revoke an application, it is still going to have access to my data until at least that access_token expires.

I would think a better to way to prevent a lookup in a relational database would be to also store the access_token in a key/value database (like redis) since that would be a bit faster. This way if someone revokes access to an application, it can delete both the record in the relational database and in the key/value data.

Am i missing something, is there a way to use encrypted data to the access_token, prevent database look up for each API call, and since be able to revoke access at anytime?

回答1:

You already know the two approaches (tokens in database vs self-contained tokens) with their pros and cons, it's a choice you have to make. Most providers go for self-contained tokens, I propose the same as a starting point, e.g. JWS/JWE.

However, instead of simple self-contained tokens, I think you can tweak it a bit and combine the best of the two worlds with a simple trick (I guess most providers may do the same). Considering token revokes an exceptional case (at least occuring much less than normal token operations), you can keep only the list of revoked tokens in a database. Validating a token, you can search for it in the list of revoked tokens: if not found, its signed or encrypted content can be used as normal. This way you still have a database, but with significantly less records and faster lookups. E.g. you can use only your key/value database instead of having both a key/value and a relational database. If you don't expect heavy traffic for your API, you may even save the whole database lookup by keeping the list of revoked tokens in memory, and e.g. periodically sweeping them from the list after they would expire anyway.