A JSON Web Token (JWT) is a compact and self-contained way of securely transmitting information between parties as a JSON object, and they are commonly used by developers in their APIs. JWTs are popular because:
In this tutorial, I will demonstrate the creation, use, and invalidation of a JWT with a simple RESTful API using Golang and the Vonage Messages API.
To complete this tutorial, you will need a Vonage API account. If you don’t have one already, you can sign up today and start building with free credit. Once you have an account, you can find your API Key and API Secret at the top of the Vonage API Dashboard.
This tutorial also uses a virtual phone number. To purchase one, go to Numbers > Buy Numbers and search for one that meets your needs. If you’ve just signed up, the initial cost of a number will be easily covered by your available credit.
A JWT is comprised of three parts:
Let’s use a simple token to understand the above concepts.
Token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdXRoX3V1aWQiOiIxZGQ5MDEwYy00MzI4LTRmZjMtYjllNi05NDRkODQ4ZTkzNzUiLCJhdXRob3JpemVkIjp0cnVlLCJ1c2VyX2lkIjo3fQ.Qy8l-9GUFsXQm4jqgswAYTAX9F4cngrl28WJVYNDwtM
Don’t worry, the token is invalid, so it won’t work on any production application.
You can navigate to jwt.to and test the token signature if it is verified or not. Use “HS512” as the algorithm. You will get the message “Signature Verified”:
To make the signature, your application will need to provide a key. This key enables the signature to remain secure-even when the JWT is decoded the signature remains encrypted. It is highly recommended to always use a secret when creating a JWT.
Since a JWT can be set to expire (be invalidated) after a particular period of time, two tokens will be considered in this application:
For a production grade application, it is highly recommended that you store JWTs in an HttpOnly
cookie. To achieve this, while sending the cookie generated from the backend to the frontend (client), a HttpOnly
flag is sent along the cookie, instructing the browser not to display the cookie through the client-side scripts. Doing this can prevent XSS (Cross Site Scripting) attacks. JWT can also be stored in browser local storage or session storage. Storing a JWT this way can expose it to several attacks such as XSS mentioned above, so it is generally less secure when compared to using `HttpOnly cookie technique.
#jwt #security #golang #programming #developer