Tokens & More Tokens! An Intro to JSON Web Tokens (JWT) in Go

Tokens & More Tokens! An Intro to JSON Web Tokens (JWT) in Go

Recently, my buddies from Blimp piqued my interest about JSON Web Tokens (JWT). You can find very detailed specs about it here and here. In this post, I want to guide you through implementing the equivalent of sessions, but with JWT.

The traditional session approach usually requires the client to store some sort of value in its cookies, while the server must have some sort of session storage where it stores that same value. For each request the client makes, the server has to make a network trip to check that the cookie's value is in the session storage.

What if there was no need for a session store? What if you could generate a token that could contain all the necessary information to prove that the request is coming from an authenticated user? You can, using JWT.


I will try to walk you through implementing this in your Go server. For this implementation I decided to go with dgrijalva's implementation.

Before we begin, we need to generate RSA keys for our project which we will use to sign the tokens. To do so, run the following commands:

Now, for your application code, lets mimic a request which will receive a JWT.

Make sure you store the token in the client. I personally like to do it in local storage, but it's completely up to you. From now on, all of your requests should contain the following header:

Authorization: Bearer TOKEN HERE

The header will be the only thing we need to identify if the user is someone we trust. Lets look at the code to parse the token out when a request is made.

And there you have it. Of course, the code here is far from optimal (no error checking, etc.) but it should hopefully give you a nice picture of how to set up JWT in your Go application. Feel free to reach out if you want an extra hand or have a better way. :)

Recommended For You

Most Popular

Send With Confidence

Partner with the email service trusted by developers and marketers for time-savings, scalability, and delivery expertise.