Securing Golang API using Json Web Token (JWT)

In this post, we will not only cover how to use Go to create a RESTful JSON API, but we will also describe how protect our API with JSON Web Tokens (JWT).

What is JSON Web Token (JWT)

According to the official site (

JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature (JWS).

JWT consists of three main components: a header object, a claims object, and a signature. These three properties are encoded using base64, then concatenated with periods as separators.

The JWT claims object contains security information about the message. For example:

  1. iss. Is the issuer of the claim. Connect uses it to identify the application making the call.
  2. iat. Issued-at time. Contains the UTC Unix time at which this token was issued. There are no hard requirements around this claim but it does not make sense for it to be significantly in the future. Also, significantly old issued-at times may indicate the replay of suspiciously old tokens.
  3. sub. The subject of this token. This is the user associated with the relevant action, and may not be present if there is no logged in user.

Authentication with JWT

JSON Web Tokens (JWT) are a more modern approach to authentication. As the web moves to a greater separation between the client and server, JWT provides a wonderful alternative to traditional cookie based authentication models.

JWTs provide a way for clients to authenticate every request without having to maintain a session or repeatedly pass login credentials to the server.

Image for post
Image for post
Token-Based Auth

Benefits of using a token-based approach

  • Cross-domain / CORS: cookies + CORS don’t play well across different domains. A token-based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information.
  • Stateless: there is no need to keep a session store, the token is a self-contained entity that conveys all the user information.
  • CDN: you can serve all the assets of your app from a CDN (e.g. javascript, HTML, images, etc.), and your server side is just the API.
  • Decoupling: you are not tied to a particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls.
  • Mobile ready: when you start working on a native platform (iOS, Android, Windows 8, etc.) cookies are not ideal when consuming a secure API (you have to deal with cookie containers). Adopting a token-based approach simplifies this a lot.
  • CRSF: since you are not relying on cookies, you don’t need to protect against cross site requests.

Organizing our Application code

Why modular? Having all of our functionality in different modules helps us in many ways:

  1. The overall application layout is easier to understand.
  2. You can see how the parts work together since modules have to be injected before use.
  3. Code is reusable since all of the necessary functionality is contained inside the module.
  4. Testing your code is much easier.

Here is how we want our file structure to look like:

Image for post
Image for post

Creating Routers

The code shown below creates a router assigning each route with his controller who runs when that endpoint is called.




Creating Controllers

Let’s create our controller’s package to manage requests and responses. Controllers will interact with our services.



Creating models

Now that we have routes and controllers in place, it’s time to create a basic user model that we can use to authenticate requests.


Creating Services


Web server

Let’s try our luck!

If we try to test it, we will obtain a valid response from server:



At this moment we have not needed to send a valid token to the server to obtain a valid response

Applying authentication with JWT

As we can see right now, our API endpoint ”/test/hello” is insecure. Let’s add our “RequireTokenAuthentication” middleware to protect it.



Now, our API test endpoint is secured and it’s necessary a valid token to obtain a valid response.

Let’s try our luck again!

If we can try again without a valid token, we’ll receive a unauthorized error response:


…for the last time!

if we add an authorization header to our request we’ll obtain a valid response from the server:\n\n1. Firstly we need to obtain a valid token:


Finally, we can do the request with our valid token:


Session control & Token Logout

The last step, or bonus step, is how we can manage user logout and invalidate his token.

Imagine that an user token has been captured from third party or simply an user wants to logout from a client and we don’t want his token to be valid again. In this way, we force he to do login again for security reasons.

To solve this problems, we’ll use Redis to store all invalid tokens until their expiration.

For that, we need the methods: Logout and IsInBlacklist. The first method sets token’s value in Redis with his expiration and the second method checks if a token is stored in redis\n\n



Can I get all the code?

Yes! of course. Here is a repo with all of the code and tests.


That’s all you have to do. JWT is a fantastic and simple way to communicate trusted information across untrusted channels. Hope you find a good use for it soon!

As well as I hope you found this post useful and helped you.

> Code less, compile quicker & execute faster

have more fun!

Written by

Engineer & Magician. CTO & Entrepreneur. Go Big or Go Home.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store