package services import ( "crypto/rand" "fmt" jwt "github.com/dgrijalva/jwt-go" ) var hmacSecret []byte // GenerateSecret generate the secret to verify JWTs func GenerateSecret() []byte { b := make([]byte, 32) rand.Read(b) return b } // InitJWTService generate the secret to verify JWTs and store it in memory func InitJWTService() { hmacSecret = GenerateSecret() fmt.Println("InitJWTService", hmacSecret) // TODO: This needs to be replaced with reading rsa keys, there needs to be a automatic generation of these if they do not exist } // Validate a jwt tokenstring func Validate(Token string) (bool, jwt.Token) { token, err := jwt.Parse(Token, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return hmacSecret, nil }) if err == nil && token.Valid { fmt.Println("Token is valid") return true, *token } fmt.Println("Token Validation failed") return false, *token } // CreateToken create a new jwt token with the provided claims func CreateToken(Claims jwt.MapClaims) string { // Create a new token object, specifying signing method and the claims // you would like it to contain. token := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims) // Sign and get the complete encoded token as a string using the secret tokenString, err := token.SignedString(hmacSecret) if err != nil { fmt.Println(err.Error()) } return tokenString }