JWTs as Email Verification Tokens
Email verification is one of the basic things most websites use to make sure that the users that registers with them are real. The user is normally asked to click a link sent on his email. When the user clicks the link, the server recognises the user based on the information passed in link and marks it as verified. There are many ways to do so, two major of them being:
1. Generate a unique code specific to user and save it in your database corresponding to that user. Send the code in the email link sent to user. When the email is clicked, recognise the user based on the code in link and mark it as verified. Secure, but requires persistent storage.
2. Encode the userId, email, link expiry information and cryptographically sign it by server. Requires no persistence, fairly secure.
JWTs happen to be perfect way to achieve the second option.
1. Widely available libraries in every language.
2. Out of box integrity protection.
If you already use JWTs for
Authorization tokens, it is easy to reimplement it for emails. I have used
go to achieve this.
The given code pretty much wraps the token generation and verification. The subject and email returned from
Verify function can be used to mark the user as validated in database. The JWT generated looks something like this:
You can use https://jwt.io to decode and check the content.
JWT tokens are usually large. In plaintext emails , it can look ugly. It can be avoided by wrapping the email link with html button.