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.
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"))
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?