What is JWT?
A JWT is a means for determining who owns JSON data. It's a cryptographically signed, encoded, URL-safe string that can hold an indefinite amount of data (unlike a cookie). When a server receives a JWT, it may be certain that the data it includes is trustworthy since the source has signed it. After a JWT is transmitted, no one can change it. It's worth noting that a JWT only ensures data ownership, not encryption. Because the JSON data you save in a JWT is serialized rather than encrypted, anyone who intercepts the token may view it.
When should JWT authentication be used?
Assume we're working on a customer for our firm's payroll API. This API is used to make payments to firm workers, access historical information about them, and lastly update the information of those individuals. Additionally, the API's developers decided that some of these tasks would require admin rights (to avoid human mistake). As a result, we'll have users with regular access who can just read data and users with super access (admins) who can also make payments and update data.
What is JWT?
However, JWTs should not be used as session tokens by default. For one point, JWT has a huge number of features and a broad reach, which raises the risk of errors by library developers or users.
Another difficulty is that because JWTs are self-contained and have no central authority to invalidate them, you can't delete them at the conclusion of a session.
To put it another way, JWTs are pretty huge. When combined with cookies, this adds a significant amount of overhead to each request.
Using JWT for API authentication
JWT is often used — and maybe the only good one — as an API authentication technique.
Google employs JWT technology to allow you to authenticate to its APIs since it is so popular and extensively utilized.
The concept is simple: when you set up the API, you acquire a secret token from the service:
On the client side, you build the token (several libraries exist for this) and sign it with the secret token.
Because the request is signed with the client's unique identity, the server will know it's that exact client when you send it as part of the API request:
How to make a single JWT token expire
What is the procedure for invalidating a single token? Changing the server secret key, which invalidates all tokens, is a no-effort solution. However, this is inconvenient for users, since their tokens may expire for no apparent reason.
One method is to add a property to your user object in the server database that references the token's creation date and time.
This value is automatically stored in the iat attribute of a token. You may compare the token's iat value to the server-side user attribute every time you check it.
Simply alter the token's server-side value to invalidate it. You can reject the token if iat is older than this.
Another option is to create a blacklist in your database that is cached in memory (or, even better, a whitelist).
Top comments (0)