Skip to content

Instantly share code, notes, and snippets.

@alinz
Created January 5, 2020 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alinz/1d67908ccff03ca2d80b86260cb82aef to your computer and use it in GitHub Desktop.
Save alinz/1d67908ccff03ca2d80b86260cb82aef to your computer and use it in GitHub Desktop.
Custom Claimer
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