Follow

Follow

Go language REST API with JWT token!

Maheshwar Ligade's photo
Maheshwar Ligade
·Apr 12, 2023·

3 min read

Play this article

Table of contents

  • Introduction:
  • What is JWT?
  • How to Implement JWT Authentication in Go Language?
  • Conclusion:

Introduction:

JSON Web Tokens (JWT) are widely used for secure authentication and authorization in web applications. JWT is an open standard for creating and verifying digital signatures, which provides a secure way of transmitting information between parties. In this article, we will explore how to implement JWT authentication in a Go language web application.

What is JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way of transmitting information securely between parties as a JSON object. The information can be verified and trusted because it is digitally signed. JWT consists of three parts: a header, a payload, and a signature.

The header contains information about the type of token and the algorithm used to sign the token. The payload contains user information, claims, and other data. The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

How to Implement JWT Authentication in Go Language?

To implement JWT authentication in a Go language web application, you can use the jwt-go package, which provides functions to create, sign, and verify JWT tokens.

JWT in Go:

To use JWTs in Go, we will use the "github.com/dgrijalva/jwt-go" package. This package provides functions to create, parse, and validate JWTs.

  1. Generating JWT Token:

    To generate a JWT token, you can create a claims object containing the user information and other data, and then use the jwt-go package to sign the claims with a secret key.

import (
    "github.com/dgrijalva/jwt-go"
)

func GenerateToken(userId int64) (string, error) {
    claims := jwt.MapClaims{}
    claims["user_id"] = userId
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    return token.SignedString([]byte("secret"))
}
  1. Verifying JWT Token:

    To verify a JWT token, you can parse the token and verify the signature using the same secret key that was used to sign the token.

func VerifyToken(tokenString string) (jwt.MapClaims, error) {
    token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
        }
        return []byte("secret"), nil
    })
    if err != nil {
        return nil, err
    }
    if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
        return claims, nil
    } else {
        return nil, fmt.Errorf("invalid token")
    }
}
  1. Authenticating Requests:

    To authenticate requests, you can add a middleware function to your HTTP handler that reads the JWT token from the Authorization header and verifies it using the VerifyToken() function.

func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        authHeader := r.Header.Get("Authorization")
        if authHeader == "" {
            http.Error(w, "missing authorization header", http.StatusUnauthorized)
            return
        }
        tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
        claims, err := VerifyToken(tokenString)
        if err != nil {
            http.Error(w, "invalid token", http.StatusUnauthorized)
            return
        }
        userId, ok := claims["user_id"].(float64)
        if !ok {
            http.Error(w, "invalid user id", http.StatusUnauthorized)
            return
        }
        r = r.WithContext(context.WithValue(r.Context(), "user_id", int64(userId)))
        next.ServeHTTP(w, r)
    })
}

Conclusion:

In this article, we explored how to use JWT tokens in Go language using the github.com/dgrijalva/jwt-go package. We learned how to create and verify JWT tokens and how to set and read claims. JWT tokens provide a secure way of transmitting information between parties and are widely used in modern web applications.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this