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

If you want to add JWT authentication to your Go application using the Echo framework, you can follow these steps. This example will guide you through creating a simple API that uses JSON Web Tokens (JWT) for authentication.

JWT, Echo, Go, Golang, Authentication, Golang API, JWT Authentication, Echo Framework
This guide demonstrates how to implement JWT authentication in a Go application using the Echo web framework, ensuring secure access to your API endpoints.

package main

import (
    "net/http"
    "github.com/labstack/echo/v4"
    "github.com/dgrijalva/jwt-go"
    "time"
)

var jwtKey = []byte("your_secret_key")

// Credentials represents the request payload
type Credentials struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

// Claims represents the JWT claims
type Claims struct {
    Username string `json:"username"`
    jwt.StandardClaims
}

// Login handles user authentication
func Login(c echo.Context) error {
    var creds Credentials
    if err := c.Bind(&creds); err != nil {
        return err
    }

    // Validate the credentials (hardcoded for example)
    if creds.Username != "user" || creds.Password != "password" {
        return echo.ErrUnauthorized
    }

    // Create the JWT claims, which includes the username and expiry time
    expirationTime := time.Now().Add(5 * time.Minute)
    claims := &Claims{
        Username: creds.Username,
        StandardClaims: jwt.StandardClaims{
            ExpiresAt: expirationTime.Unix(),
        },
    }

    // Create the JWT token
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenString, err := token.SignedString(jwtKey)
    if err != nil {
        return err
    }

    // Return the token
    return c.JSON(http.StatusOK, echo.Map{
        "token": tokenString,
    })
}

// Protected route
func Protected(c echo.Context) error {
    user := c.Get("user").(*jwt.Token)
    claims := user.Claims.(*Claims)
    username := claims.Username

    return c.String(http.StatusOK, "Welcome "+username+"!")
}

// Middleware to validate token
func IsAuthenticated(next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
        token := c.Request().Header.Get("Authorization")
        if token == "" {
            return echo.ErrUnauthorized
        }

        claims := &Claims{}
        tkn, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {
            return jwtKey, nil
        })

        if err != nil || !tkn.Valid {
            return echo.ErrUnauthorized
        }

        c.Set("user", tkn)
        return next(c)
    }
}

func main() {
    e := echo.New()

    e.POST("/login", Login)
    e.GET("/protected", IsAuthenticated(Protected))

    e.Logger.Fatal(e.Start(":8080"))
}
    

JWT Echo Go Golang Authentication Golang API JWT Authentication Echo Framework