How do I add authentication with JWT with Fiber in Go?

In this example, we will demonstrate how to implement JWT (JSON Web Token) authentication using the Fiber web framework in Go. This approach helps secure your API endpoints, allowing only authenticated users to access them.

Go, Fiber, JWT, JSON Web Token, Authentication, Go web framework, Secured API, Middleware, Golang

Learn how to secure your Go applications with Fiber using JWT authentication. This guide covers the necessary steps to implement secure endpoint access, making your API robust against unauthorized access.


package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/dgrijalva/jwt-go"
    "time"
)

var jwtSecret = []byte("your_secret_key")

func main() {
    app := fiber.New()

    app.Post("/login", login)          // Login route to generate the token
    app.Get("/protected", protected)    // Protected route to access with token

    app.Listen(":3000")
}

func login(c *fiber.Ctx) error {
    // In a real application, you would validate user credentials here
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
        "user": "exampleUser",
        "exp":  time.Now().Add(time.Hour * 72).Unix(),
    })

    tokenString, err := token.SignedString(jwtSecret)
    if err != nil {
        return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Could not create token"})
    }

    return c.JSON(fiber.Map{"token": tokenString})
}

func protected(c *fiber.Ctx) error {
    tokenString := c.Get("Authorization")
    if tokenString == "" {
        return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "No token provided"})
    }

    claims := &jwt.MapClaims{}
    token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
        return jwtSecret, nil
    })

    if err != nil || !token.Valid {
        return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Invalid token"})
    }

    return c.JSON(fiber.Map{"message": "Welcome to the protected route!", "user": claims["user"]})
}
    

Go Fiber JWT JSON Web Token Authentication Go web framework Secured API Middleware Golang