Add an Authentication Feature in REST API
Learn how to add authentication features in the REST API application.
We'll cover the following...
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.
package utilsimport ("strconv""time""github.com/golang-jwt/jwt/v4")// GenerateNewAccessToken returns JWT tokenfunc GenerateNewAccessToken() (string, error) {// get the JWT secret key from .env filesecret := GetValue("JWT_SECRET_KEY")// get the JWT token expire time from .env fileminutesCount, _ := strconv.Atoi(GetValue("JWT_SECRET_KEY_EXPIRE_MINUTES_COUNT"))// create a JWT claim objectclaims := jwt.MapClaims{}// add expiration time for the tokenclaims["exp"] = time.Now().Add(time.Minute * time.Duration(minutesCount)).Unix()// create a new JWT token with the JWT claim objecttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)// convert the token in a string formatt, err := token.SignedString([]byte(secret))// if conversion failed, return the errorif err != nil {return "", err}// return the tokenreturn t, nil}
Authentication helper
In the code above, the JWT Token is created in ...