Skip to content

Instantly share code, notes, and snippets.

@juanpabloaj
Created December 22, 2020 20:35
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 juanpabloaj/5083f65079efa00116a05bb92d41f293 to your computer and use it in GitHub Desktop.
Save juanpabloaj/5083f65079efa00116a05bb92d41f293 to your computer and use it in GitHub Desktop.
JWT go example signing methods
import (
"fmt"
"io/ioutil"
"time"
"github.com/dgrijalva/jwt-go"
)
func signingWithHMAC() {
sampleSecret := []byte("your-256-bit-secret")
newToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"foo": "bar",
"nbf": time.Now().Unix(),
})
tokenString, err := newToken.SignedString(sampleSecret)
if err != nil {
fmt.Errorf("%v", err)
}
fmt.Println("HS token:", tokenString)
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return sampleSecret, nil
})
if err != nil {
fmt.Printf("%v", err)
}
claims, ok := token.Claims.(jwt.MapClaims)
if ok && token.Valid {
fmt.Println(claims)
}
}
func signingWithRSA() {
privateKeyPem, _ := ioutil.ReadFile("sample_key")
publicKeyPem, _ := ioutil.ReadFile("sample_key.pub")
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKeyPem)
if err != nil {
fmt.Errorf("%v", err)
}
publicKey, err := jwt.ParseRSAPublicKeyFromPEM(publicKeyPem)
if err != nil {
fmt.Errorf("%v", err)
}
newToken := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"foo": "bar",
"nbf": time.Now().Unix(),
})
tokenString, err := newToken.SignedString(privateKey)
if err != nil {
fmt.Errorf("%v", err)
}
fmt.Println("RSA token:", tokenString)
token, 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"])
}
return publicKey, nil
})
claims, ok := token.Claims.(jwt.MapClaims)
if ok && token.Valid {
fmt.Println(claims)
}
}
func main() {
signingWithHMAC()
signingWithRSA()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment