DEV Community

Muhammad Adam
Muhammad Adam

Posted on

1 1

Do You Need A Implementation Jwt In Go (Golang)?

Go is becoming very popular for backend development, and JWT’s are one of the most popular ways to handle authentication on API requests. In this article, we are going to go over the basics of JWT’s and how to implement a secure authentication strategy in Go! Let’s go

What is a JWT?

JSON Web Token (JWT, pronounced /dʒɒt/, same as the word “jot”[1]) is a proposed Internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims. The tokens are signed either using a private secret or a public/private key.

JWTs have essentially encoded JSON objects that have been signed by the server, proving their authenticity.

For example, when a user login into a website secured via JWTs, the flow should look something like this:

  1. The user sends a username and password to the server

  2. The server verifies username and password are correct

  3. The server creates a JSON object that looks like this:
    {“username”: “adam”}

  4. The server encodes and signs the JSON object, creating a JWT:
    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

  5. The user’s web client saves the JWT for later use

  6. When the user makes a request to a protected endpoint, the JWT is passed along in an HTTP header

  7. The server checks the signature on the JWT to make sure the JWT was originally created by the same server

  8. The server reads the claims and gives permission to the request to operate as “adam”

Create a JWT

Before we create a JWT, we are going to use a library for dealing with JSON Web Token in go using golang-jwt. Make sure you have the code cloned in your local by running the below command :

go get github.com/golang-jwt/jwt/v4
Enter fullscreen mode Exit fullscreen mode

This implies that we presume the server that generates the JWTs will also be the sole server that verifies them.

First, define a struct that will be used to represent claims or identity for users data :

The jwt.StandardClaims struct contains useful fields like expiry, issuer name, Subject and etc. Now we will create some actual claims for the user that just logged in :

After that, Create an unsigned token from the claims :

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
Enter fullscreen mode Exit fullscreen mode

Sign the token using a secure private key. Make sure you use a real private key, preferably at least 256 bits in length:

signedToken, err := token.SignedString([]byte(“secureSecretText”))
Enter fullscreen mode Exit fullscreen mode

Now the signed token can be sent back to the client.

Validating a JWT

When a client requests a secured endpoint, we may use the following steps to validate the JWT.

Note: To use the Authorization HTTP header is idiomatic:

Authorization: Bearer {jwt}
Enter fullscreen mode Exit fullscreen mode

After obtaining the JWT, use the same private key to validate the claims and verify the signature.

token, err := jwt.ParseWithClaims(
    jwtFromHeader,
    &customClaims{},
    func(token *jwt.Token) (interface{}, error) {
        return []byte("secureSecretText"), nil 
    },
)
Enter fullscreen mode Exit fullscreen mode

The err variable will not be null if the claims have been tampered with. Parse the following claims from the token:

claims, ok := token.Claims.(*customClaims)
if !ok {
    return errors.New("Couldn't parse claims")
}
Enter fullscreen mode Exit fullscreen mode

Check if the token is expired:

if claims.ExpiresAt < time.Now().UTC().Unix() {
    return errors.New("JWT is expired")
}
Enter fullscreen mode Exit fullscreen mode

You now know the username of the authenticated user!

username := claims.Username
Enter fullscreen mode Exit fullscreen mode

For full examples take a look at this example.

Thanks For Reading!

Available for a new project! Let’s have a talk bangadam.dev@gmail.com

Neon image

Set up a Neon project in seconds and connect from a Go application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (0)

AI Agent image

How to Build an AI Agent with Semantic Kernel (and More!)

Join Developer Advocate Luce Carter for a hands-on tutorial on building an AI-powered dinner recommendation agent. Discover how to integrate Microsoft Semantic Kernel, MongoDB Atlas, C#, and OpenAI for ingredient checks and smart restaurant suggestions.

Watch the video →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay