Skip to content

Instantly share code, notes, and snippets.

@aisensiy
Created January 17, 2019 14:42
Show Gist options
  • Save aisensiy/08f3cbde29f848f9db29f22031564673 to your computer and use it in GitHub Desktop.
Save aisensiy/08f3cbde29f848f9db29f22031564673 to your computer and use it in GitHub Desktop.
Jwt in Golang
package main
import (
"fmt"
jwt "github.com/dgrijalva/jwt-go"
)
func main() {
// sample token string taken from the New example
tokenString := "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJiODgxN2YzMyIsImV4cCI6MTU0NzczOTM4Nn0.ZGlX206W2hIdWqluXxv359--jUHYl669EQ0pZyS-0fumzMVvDEi1w5w7wFAOlOT0DlDGTCHss8k0SygLdo8gQw"
// 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.SigningMethodHMAC); !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 []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
fmt.Println(claims["exp"])
} else {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment