DEV Community

Cover image for How to implement token based authentication using JWT in Golang?
Darpan Vithani for Canopas Software

Posted on

How to implement token based authentication using JWT in Golang?

JWT(JSON web token) is a token format used for authentication in any application. jwt.io provides a web interface to check the JWT tokens and a user guide for understanding the token structure.

JWT tokens contain three parts:

  • Header - (contains the type of token and signing algorithm of the token)
  • Signature — (base64 key used to verify the message wasn’t changed along the way)
  • Payload — (contains actual data that is claims used to create tokens)

We will implement Golang JWT authentication using a go-jwt package.

We are using two types of tokens for authentication in the applications.

  • Access Token: A string used to access protected resources on the client side. Every token has a specific scope, lifetime, and other valid attributes. We can set lifetime as per our needs(1 hour or 1 day).
  • Refresh Token: A string that is used to obtain an access token. It will be created at the time of issuing an access token for authorization. Its lifetime should be greater than the access token(1 month or 1 year).

Keep in mind that, these tokens are not only JWT-specific. They provide a way to authorize resources. We can create these tokens using JWT or any other format.

For step by step implementation, visit canopas blog.

Top comments (0)