Skip to content

Instantly share code, notes, and snippets.

@alissonperez
Last active March 5, 2021 12:45
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 alissonperez/7a9291f3a8caf132c217e208659a9910 to your computer and use it in GitHub Desktop.
Save alissonperez/7a9291f3a8caf132c217e208659a9910 to your computer and use it in GitHub Desktop.
JWT Go - RSA generation and validation example
// Generate keys (based in https://gist.github.com/nghiaht/224f7fe04ea591c6d2fddbee6c173379)
// Gen private keys:
// openssl genpkey -algorithm RSA -out private.pem -pkeyopt rsa_keygen_bits:2048
// Gen public keys:
// openssl rsa -pubout -in private.pem -out public_key.pem
package main
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"io/ioutil"
"time"
)
type MyCustomClaims struct {
Foo string `json:foo`
*jwt.StandardClaims
}
func genToken() (string, error) {
privateKey, _ := ioutil.ReadFile("keys/private.pem")
parsedPrivateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKey)
if err != nil {
fmt.Printf("Parse error private key %s\n\n", err)
}
// Create the token
token := jwt.New(jwt.GetSigningMethod("RS256"))
claims := make(jwt.MapClaims)
claims["exp"] = time.Now().Add(time.Hour * time.Duration(1)).Unix()
claims["foo"] = "bar"
token.Claims = claims
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString(parsedPrivateKey)
if err != nil {
fmt.Printf("Err: %s\n\n", err)
return "", err
}
return tokenString, nil
}
func validateToken(token string) error {
publicKey, _ := ioutil.ReadFile("keys/public_key.pem")
parsedPublicKey, err := jwt.ParseRSAPublicKeyFromPEM(publicKey)
if err != nil {
fmt.Printf("Parse error public key %s\n\n", err)
}
keyLookupFunc := func(token *jwt.Token) (interface{}, error) {
return parsedPublicKey, nil
}
tokenResult, err := jwt.ParseWithClaims(token, &MyCustomClaims{}, keyLookupFunc)
if err == nil {
claims := tokenResult.Claims.(*MyCustomClaims)
fmt.Printf("Token for user %v expires %v\n\n", claims.Foo, claims.StandardClaims.ExpiresAt)
}
if err == nil && tokenResult.Valid {
return nil
} else {
return fmt.Errorf("Token invalid: err: %s\n\n", err)
}
}
func main() {
tokenString, err := genToken()
if err != nil {
fmt.Printf("Error when generating token %s\n\n", err)
return
}
err = validateToken(tokenString)
if err != nil {
fmt.Printf("Error to validate token %s\n\n", err)
return
}
fmt.Printf("Valid token %s\n\n", tokenString)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment