Reading a JWT in Go

jwt-go also gives us the API to parse a given JWT string. The Parse function takes a string and key function as arguments. The key function is a custom function that validates whether the algorithm is proper or not. Let us say this is a sample token string generated by the preceding encoding:

tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoiMTUwODc0MTU5MTQ2NiJ9.5m6KkuQFCgyaGS_xcVy4xWakwDgtAG3ILGGTBgYVBmE"

We can parse and get back the original JSON using:

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    // key function
    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
        return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
    }
    return "my_secret_key", nil
})

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// Use claims for authorization if token is valid fmt.Println(claims["username"], claims["iat"]) } else { fmt.Println(err) }

token.Claims is implemented by a map called MapClaims. We can get the original JSON key-value pairs from that map.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.77.208