Skip to content

Instantly share code, notes, and snippets.

@d2lam
Created January 26, 2017 23:42
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 d2lam/8eae57abe9c5b6ee501642dcb1997cf8 to your computer and use it in GitHub Desktop.
Save d2lam/8eae57abe9c5b6ee501642dcb1997cf8 to your computer and use it in GitHub Desktop.
JWT validation
package main
import (
"fmt"
"io/ioutil"
"github.com/screwdriver-cd/jwt/jwt-go"
)
func main() {
// sample token string taken from the New example
tokenString := "token"
keyData, _ := ioutil.ReadFile("pubkey")
key, _ := jwt.ParseRSAPublicKeyFromPEM(keyData)
// Parse takes the token string and a function for looking up the key. The latter is especially
// useful if you use multiple keys for your application. The standard is to use 'kid' in the
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return key, nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
fmt.Println(claims["username"], claims["scope"])
} else {
fmt.Printf("ERROR: %v\n", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment