From 45c52c4dbfabf9b854022df672cd02f62da7a947 Mon Sep 17 00:00:00 2001 From: John Schaeffer Date: Wed, 14 Feb 2024 14:37:06 -0500 Subject: [PATCH] Add config option for JWT issuer and require iat/exp claims in token (#16) Runtime users should be validating the JWT issuer in addition to the JWKS. This commit adds logic to configure the expected issuer for a JWT and updates the token parser to require the "iat" and "exp" claims be present for a given token. Additionally, this commit fixes an error where command line flags were not being bound to Viper configs properly. Signed-off-by: John Schaeffer --- cmd/serve.go | 4 ++++ config.example.yaml | 3 ++- internal/jwt/config.go | 2 ++ internal/jwt/validator.go | 14 +++++++++++--- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/cmd/serve.go b/cmd/serve.go index ca6bc52c..c88656bc 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -32,6 +32,10 @@ func init() { jwt.AddFlags(cmdFlags) permissions.AddFlags(cmdFlags) server.AddFlags(cmdFlags) + + if err := viper.BindPFlags(cmdFlags); err != nil { + panic(err) + } } func serve(_ context.Context, _ *viper.Viper, cfg config.Config) error { diff --git a/config.example.yaml b/config.example.yaml index 2594d860..023cc048 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -3,6 +3,7 @@ server: permissions: host: permissions-api.enterprise.dev jwt: - jwksuri: https://iam.enterprise.dev/jwks.json + jwksuri: https://identity-api.enterprise.dev/jwks.json + issuer: https://identity-api.enterprise.dev/ tracing: enabled: false diff --git a/internal/jwt/config.go b/internal/jwt/config.go index 17fd3158..09c377b6 100644 --- a/internal/jwt/config.go +++ b/internal/jwt/config.go @@ -6,10 +6,12 @@ import ( // Config represents the configuration for a JWT validator. type Config struct { + Issuer string JWKSURI string } // AddFlags sets the command line flags for JWT validation. func AddFlags(flags *pflag.FlagSet) { + flags.String("jwt.issuer", "", "Issuer to use for JWT validation") flags.String("jwt.jwksuri", "", "JWKS URI to use for JWT validation") } diff --git a/internal/jwt/validator.go b/internal/jwt/validator.go index 83a57d03..f5419b15 100644 --- a/internal/jwt/validator.go +++ b/internal/jwt/validator.go @@ -18,7 +18,8 @@ type Validator interface { } type validator struct { - kf jwt.Keyfunc + kf jwt.Keyfunc + parser *jwt.Parser } // NewValidator creates a validator with the given configuration. @@ -51,15 +52,22 @@ func NewValidator(config Config) (Validator, error) { return nil, err } + parser := jwt.NewParser( + jwt.WithIssuedAt(), + jwt.WithExpirationRequired(), + jwt.WithIssuer(config.Issuer), + ) + out := &validator{ - kf: kf.Keyfunc, + kf: kf.Keyfunc, + parser: parser, } return out, nil } func (v *validator) ValidateToken(tokenString string) (map[string]string, error) { - tok, err := jwt.Parse(tokenString, v.kf) + tok, err := v.parser.Parse(tokenString, v.kf) if err != nil { return nil, err }