Created
January 26, 2017 23:42
-
-
Save d2lam/8eae57abe9c5b6ee501642dcb1997cf8 to your computer and use it in GitHub Desktop.
JWT validation
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" | |
"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