Last active
May 31, 2019 19:34
-
-
Save sle-c/a31665085d8141c3f14d240e0d47eb85 to your computer and use it in GitHub Desktop.
Parse JWT token
This file contains hidden or 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 goliauth | |
import ( | |
"fmt" | |
jwt "github.com/dgrijalva/jwt-go" | |
) | |
// Claims is an alias for MapClaims | |
type Claims = jwt.MapClaims | |
// StandardClaims wraps jwt standard claims type | |
type StandardClaims jwt.StandardClaims | |
// NewClaims create a Claims type | |
func NewClaims(data map[string]interface{}) Claims { | |
newClaims := Claims(data) | |
return newClaims | |
} | |
// ParseJWT parses a JWT and returns Claims object | |
// Claims can be access using index notation such as claims["foo"] | |
func ParseJWT(tokenString string, key string) (Claims, error) { | |
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"]) | |
} | |
return []byte(key), nil | |
}) | |
if token.Valid { | |
if claims, ok := token.Claims.(Claims); ok { | |
return claims, nil | |
} | |
return nil, err | |
} else if ve, ok := err.(*jwt.ValidationError); ok { | |
if ve.Errors&jwt.ValidationErrorMalformed != 0 { | |
return nil, err | |
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 { | |
// Token is either expired or not active yet | |
return nil, err | |
} else { | |
return nil, err | |
} | |
} else { | |
return nil, err | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment