github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/crypto/jwt.go (about)

     1  package crypto
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	jwt "github.com/golang-jwt/jwt/v5"
     8  )
     9  
    10  // SigningMethod is the algorithm choosed for signing JWT.
    11  // Currently, it is HMAC-SHA-512
    12  var SigningMethod = jwt.SigningMethodHS512
    13  
    14  // NewJWT creates a JWT token with the given claims,
    15  // and signs it with the secret
    16  func NewJWT(secret []byte, claims jwt.Claims) (string, error) {
    17  	token := jwt.NewWithClaims(SigningMethod, claims)
    18  	return token.SignedString(secret)
    19  }
    20  
    21  // ParseJWT parses a string and checkes that is a valid JSON Web Token
    22  func ParseJWT(tokenString string, keyFunc jwt.Keyfunc, claims jwt.Claims) error {
    23  	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
    24  		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
    25  			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
    26  		}
    27  		return keyFunc(token)
    28  	})
    29  	if err != nil {
    30  		return err
    31  	}
    32  	if !token.Valid {
    33  		return errors.New("Invalid JSON Web Token")
    34  	}
    35  	return nil
    36  }