From 36bcd3bd82240c4621b0900cfebeb16f727fe67b Mon Sep 17 00:00:00 2001 From: ben-toogood Date: Wed, 19 Feb 2020 08:51:43 +0000 Subject: [PATCH] Improve JWT Package Errors (#1206) Co-authored-by: Asim Aslam --- auth/jwt/jwt.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/auth/jwt/jwt.go b/auth/jwt/jwt.go index e0719682..d60c9361 100644 --- a/auth/jwt/jwt.go +++ b/auth/jwt/jwt.go @@ -17,6 +17,9 @@ var ErrEncodingToken = errors.New("An error occured while encoding the JWT") // ErrInvalidToken is returned when the token provided is not valid var ErrInvalidToken = errors.New("An invalid token was provided") +// ErrMissingToken is returned when no token is provided +var ErrMissingToken = errors.New("A valid JWT is required") + // NewAuth returns a new instance of the Auth service func NewAuth(opts ...auth.Option) auth.Auth { svc := new(svc) @@ -64,7 +67,7 @@ func (s *svc) Generate(id string, ops ...auth.GenerateOption) (*auth.Account, er options := auth.NewGenerateOptions(ops...) account := jwt.NewWithClaims(jwt.SigningMethodRS256, AuthClaims{ id, options.Roles, options.Metadata, jwt.StandardClaims{ - Subject: "TODO", + Subject: id, ExpiresAt: time.Now().Add(time.Hour * 24).Unix(), }, }) @@ -89,6 +92,10 @@ func (s *svc) Revoke(token string) error { // Validate a JWT func (s *svc) Validate(token string) (*auth.Account, error) { + if token == "" { + return nil, ErrMissingToken + } + res, err := jwt.ParseWithClaims(token, &AuthClaims{}, func(token *jwt.Token) (interface{}, error) { return jwt.ParseRSAPublicKeyFromPEM(s.options.PublicKey) })