Skip to content

Instantly share code, notes, and snippets.

@lonelyelk
Created June 15, 2018 09:47
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 lonelyelk/bb5490b616d04f3e7818c42968d358cc to your computer and use it in GitHub Desktop.
Save lonelyelk/bb5490b616d04f3e7818c42968d358cc to your computer and use it in GitHub Desktop.
Asymmetric JWT token with Go
ssh-keygen -t rsa -b 2048 -f jwtRS256.key
openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub
package main
import (
"fmt"
"io/ioutil"
"time"
jwt "gopkg.in/dgrijalva/jwt-go.v3"
)
func main() {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"foo": "bar",
"nbf": time.Date(2018, 06, 14, 12, 0, 0, 0, time.UTC).Unix(),
})
privateKeyString, err := ioutil.ReadFile("./jwtRS256.key")
if err != nil {
fmt.Printf("Error reading private key: %v", err)
return
}
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKeyString)
if err != nil {
fmt.Printf("Error converting private key: %v", err)
return
}
tokenString, err := token.SignedString(privateKey)
if err != nil {
fmt.Printf("Error signing token: %v", err)
return
}
fmt.Println("SIGNED:")
fmt.Println(tokenString)
// Verify:
readToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
publicKeyString, err := ioutil.ReadFile("./jwtRS256.key.pub")
if err != nil {
return nil, fmt.Errorf("Error reading public key: %v", err)
}
publicKey, err := jwt.ParseRSAPublicKeyFromPEM(publicKeyString)
if err != nil {
return nil, fmt.Errorf("Error converting public key: %v", err)
}
return publicKey, nil
})
if claims, ok := readToken.Claims.(jwt.MapClaims); ok && readToken.Valid {
fmt.Println("VERIVIED:")
fmt.Println(claims["foo"], claims["nbf"])
} else {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment