Created
January 5, 2020 16:37
-
-
Save alinz/1d67908ccff03ca2d80b86260cb82aef to your computer and use it in GitHub Desktop.
Custom Claimer
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
type Claims struct { | |
AccountID string `json:"account_id"` | |
GroupID string `json:"group_id"` | |
jwtgo.StandardClaims | |
} | |
// Encode | |
func (c *Claims) Encode(secretKey []byte) (string, error) { | |
const op = errors.Op("jwt.Claims.Encode") | |
token := jwtgo.NewWithClaims(jwtgo.SigningMethodHS256, c) | |
tok, err := token.SignedString(secretKey) | |
if err != nil { | |
return "", errors.E(op, err) | |
} | |
return tok, nil | |
} | |
// Decode tries to decode given token by using secret key | |
func (c *Claims) Decode(secretKey []byte, jwtToken string) error { | |
const op = errors.Op("jwt.Claims.Decode") | |
token, err := jwtgo.ParseWithClaims(jwtToken, c, func(token *jwtgo.Token) (interface{}, error) { | |
if _, ok := token.Method.(*jwtgo.SigningMethodHMAC); !ok { | |
return nil, errors.E(op, "unexpected signing method") | |
} | |
return secretKey, nil | |
}) | |
if err != nil { | |
return err | |
} | |
if claims, ok := token.Claims.(*Claims); ok && token.Valid { | |
c.AccountID = claims.AccountID | |
c.GroupID = claims.GroupID | |
return nil | |
} | |
return errors.E(op, "not valid") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment