DEV Community

Muhammad Adam
Muhammad Adam

Posted on

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

Top comments (0)