Created
June 15, 2018 09:47
-
-
Save lonelyelk/bb5490b616d04f3e7818c42968d358cc to your computer and use it in GitHub Desktop.
Asymmetric JWT token with Go
This file contains 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
ssh-keygen -t rsa -b 2048 -f jwtRS256.key | |
openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub |
This file contains 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
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