How to do JWT authentication in Golang

JWT Authentication with Golang

JSON Web Tokens (JWTs) are a popular method for dealing with online authentication, and you can implement JWT authentication in any server-side programming language.

For background reading JWTs in general, I recommend learning more about JWTs, best practices, and securing RESTful APIs with JWTs.

This article is aimed at helping you get started with implementing JWT authentication in your Go web applications using the golang-jwt package.

The golang-jwt package is the most popular package for implementing JWTs in Go, owing to its features and ease of use. The golang-jwt package provides functionality for generating and validating JWTs.

Prerequisites

You’ll need to meet these basic requirements to get the most out of this tutorial.

  • Go 1.16 or later installed on your machine (for security reasons)
  • Experience building web applications in Golang or any other language (optional)

Table of Contents

  • Getting started with the Golang-JWT package
  • Setting up a web server in Go
  • Generating JWTs using the Golang-JWT package
  • Verifying JWT tokens
  • Extracting claims from JWT tokens

How to start with the Golang-JWT package

After setting up your Go workspace and initializing the Go modules file go.mod, run this command on your terminal in the workspace directory to install the golang-jwt package:

go get github.com/golang-jwt/jwt

After you installed the golang-jwt, create a Go file, and import these packages and modules.

import (
   "log"
    "encoding/json"
   "github.com/golang-jwt/jwt"
   "net/http"
   "time"
)

You’ll use these packages in this tutorial to log errors, set up a server, and set the token expiration time.

Setting up a web server in Golang

Let’s start with creating a simple web server with an endpoint that will be secured with a JWT.

func main() {
   http.HandleFunc("/home", handlePage)
   err := http.ListenAndServe(":8080", nil)
   if err != nil {
      log.Println("There was an error listening on port :8080", err)
   }

}

The main function sets up the home endpoint with a handler function handlePage that you’ll set up. The handlePage function will secure the page using JWTs. The server is set to listen on port :8080, but you can use any port of your choice.