Last active
March 5, 2021 12:45
-
-
Save alissonperez/7a9291f3a8caf132c217e208659a9910 to your computer and use it in GitHub Desktop.
JWT Go - RSA generation and validation example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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