Search⌘ K

Add an Authentication Feature in REST API

Learn how to add authentication features in the REST API application.

Create basic authentication functionalities

Before adding basic authentication, we create a helper to generate tokens for authentication purposes in the auth.go file inside the utils directory.

Go (1.18.2)
package utils
import (
"strconv"
"time"
"github.com/golang-jwt/jwt/v4"
)
// GenerateNewAccessToken returns JWT token
func GenerateNewAccessToken() (string, error) {
// get the JWT secret key from .env file
secret := GetValue("JWT_SECRET_KEY")
// get the JWT token expire time from .env file
minutesCount, _ := strconv.Atoi(GetValue("JWT_SECRET_KEY_EXPIRE_MINUTES_COUNT"))
// create a JWT claim object
claims := jwt.MapClaims{}
// add expiration time for the token
claims["exp"] = time.Now().Add(time.Minute * time.Duration(minutesCount)).Unix()
// create a new JWT token with the JWT claim object
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// convert the token in a string format
t, err := token.SignedString([]byte(secret))
// if conversion failed, return the error
if err != nil {
return "", err
}
// return the token
return t, nil
}
Authentication helper

In the code above, the JWT Token is created in GenerateNewAccessToken(). Before the token is created, some token metadata, including ...