Skip to content

Using JSON Web Token(JWT) with golang

package library

import (
	"models"
	"errors"

	"github.com/dgrijalva/jwt-go"
)

//EncodeJWT encodes claims and returns a jwt code
func EncodeJWT(key []byte, claims jwt.Claims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)

	encodedToken, err := token.SignedString(key)
	if err != nil {
		return "", err
	}
	return encodedToken, nil
}

//DecodeJWT decodes token and returns claims
func DecodeJWT(key []byte, encodedToken string, claims jwt.Claims) error {
	token, err := jwt.ParseWithClaims(encodedToken, claims, func(token *jwt.Token) (interface{}, error) {
		return key, nil
	})

	if err != nil {
		if err == jwt.ErrSignatureInvalid {
			return err
		}
		//return statusbadrequest
	}
	if !token.Valid {
		return errors.New("unauthorized")
	}

	return nil
}

Test code

func main() {
	expirationTime := time.Now().Add(time.Minute * 5)

	claims := &models.Claims{
		Username: "abcdef",
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
		},
	}

	jwtSecretKey := []byte("jwtsecretkey")
	jwtToken, _ := library.EncodeJWT(jwtSecretKey, claims)
	fmt.Println(jwtToken)
	decodedClaims := &models.Claims{}
	library.DecodeJWT(jwtSecretKey, jwtToken, decodedClaims)
	fmt.Println(decodedClaims.Username)
}
Published inGolang

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *