DEV Community

Jacob Clark
Jacob Clark

Posted on

Best practices for authentication in an oauth API flow?

I'm building an application that users Spotifys API OAuth for Authorisation, the access token that is ultimately recieved by my app from Spotify is stored as a HttpOnly Cookie on the client that requested my application in order to pass to subsequent API requests.

What are best practices for ensuring authentication when working with APIs in this way? E.g the user is who they say they are on subsequent requests.

Top comments (2)

bugfrog profile image

There are a lot of ways to approach authentication workflows, especially with so many variables in play. Here are detailed diagrams of almost 30 different flows, depending on whether you are building a web app, single page app, or native mobile app. I'd paste it in here, but it's a lot. Hope it helps.

jdforsythe profile image
Jeremy Forsythe • Edited

JWT with a key pair is a good way to prevent DB lookups or keeping sessions for subsequent requests. You can guarantee the JWT was signed with your private key, only available on your server. The public key can be cached, e.g. in redis, for fast lookup to decrypt the JWT and then you can trust the user object inside without a DB lookup. Additionally, you can easily rotate the key pair and "log out" everyone if you need to.

Applying this to a token received from a third party is possible, just wrap the value of their token in a JWT and use the private key to encrypt it.