Skip to content

Instantly share code, notes, and snippets.

@aicam
Created June 5, 2020 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aicam/eb87fe171e1a44f51b6ece3980582fbc to your computer and use it in GitHub Desktop.
Save aicam/eb87fe171e1a44f51b6ece3980582fbc to your computer and use it in GitHub Desktop.
This file contains two function to create and sign JWT token, the generation needs a token which is declared global in file but token key passes to check function
package cryptoUtils
import (
"github.com/dgrijalva/jwt-go"
"time"
)
type Credentials struct {
Password string `json:"password"`
Username string `json:"username"`
}
// TODO: register all tokens at environmental variables
var JWTKey = []byte("ServerToken")
// Create a struct that will be encoded to a JWT.
// We add jwt.StandardClaims as an embedded type, to provide fields like expiry time
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
}
func generateJWT(username string) (string, error) {
// Declare the expiration time of the token
// here, we have kept it as 5 minutes
expirationTime := time.Now().Add(5 * time.Minute)
// Create the JWT claims, which includes the username and expiry time
claims := &Claims{
Username: username,
StandardClaims: jwt.StandardClaims{
// In JWT, the expiry time is expressed as unix milliseconds
ExpiresAt: expirationTime.Unix(),
},
}
// Declare the token with the algorithm used for signing, and the claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Create the JWT string
return token.SignedString(JWTKey)
}
func CheckJWTToken(tknStr string, jwtKey []byte) error {
claims := &Claims{}
// Parse the JWT string and store the result in `claims`.
// Note that we are passing the key in this method as well. This method will return an error
// if the token is invalid (if it has expired according to the expiry time we set on sign in),
// or if the signature does not match
_, err := jwt.ParseWithClaims(tknStr, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment