JSON web tokens (JWT) and token auth are two different types of authentication.
Token authentication, or sometimes referred to as token auth, works by generating a random string (a token) for the user when they authenticate. The token is then included in the HTTP auth header on each subsequent request, and then validated by checking the database on each request.
The benefit of the token auth is that it’s the simplest form of authentication that keeps the user’s credentials secure (because the token is sent with each request instead of a username and password). This way the users credentials (username/password) is only sent to the server once and never stored/cached for future requests, which keeps their details secure.
Tokens can also be revoked if desired to force users to re-authenticate.
The downside of token auth is that the database is hit at least once for every request. This is fine for small to medium scale apps, but may be an issue if you have to handle large volumes (100k+) requests in a short space of time, because of the sheer number of database requests required.
JSON Web Tokens (JWT)
JWT is a different approach which uses encryption and hashing techniques to validate the token instead of database checks. It starts the same as token auth, by sending the username and password and validating it against the database.
Once validated, the server generates a token based on a secret key which only the server knows. The client can then include this token in the HTTP headers of subsequent requests, and the server can validate it using the secret key without hitting the database.
The token usually converts to a JSON object with the details about the authenticating user (typically a user ID) so the server knows which user is authenticating without accessing the database at all.
Each token is valid for a fixed period of time, after which the server must use a refresh token to request a new one. This allows the server to block access to clients if required.
The benefit of JWT is that it is more scalable, because it requires less database hits. The downside is that it’s more complicated to implement.
To summarise, token authentication is great if you are looking for a simple auth system which is easy to implement and maintain. However, you might want to consider investing the extra time to implement JWT if you anticipate lots of traffic to your API.
I hope you found this post useful. If you are interested in learning how to build APIs using token authentication, check out our courses below: