From 669364985e7b96f350dc489b3f30b513c7c0b569 Mon Sep 17 00:00:00 2001 From: Ben Toogood Date: Wed, 29 Apr 2020 09:21:17 +0100 Subject: [PATCH] JWT auth implementation --- auth/jwt/jwt.go | 82 +++++++++++++++++++++++++++++++++++++++++++++++ config/cmd/cmd.go | 2 ++ 2 files changed, 84 insertions(+) create mode 100644 auth/jwt/jwt.go diff --git a/auth/jwt/jwt.go b/auth/jwt/jwt.go new file mode 100644 index 00000000..9eb7b864 --- /dev/null +++ b/auth/jwt/jwt.go @@ -0,0 +1,82 @@ +package jwt + +import ( + "errors" + + "github.com/micro/go-micro/v2/auth" + "github.com/micro/go-micro/v2/auth/token" + jwtToken "github.com/micro/go-micro/v2/auth/token/jwt" +) + +// NewAuth returns a new instance of the Auth service +func NewAuth(opts ...auth.Option) auth.Auth { + j := new(jwt) + j.Init(opts...) + return j +} + +// jwt is the service implementation of the Auth interface +type jwt struct { + options auth.Options + jwt token.Provider +} + +func (j *jwt) String() string { + return "jwt" +} + +func (j *jwt) Init(opts ...auth.Option) { + for _, o := range opts { + o(&j.options) + } + + j.jwt = jwtToken.NewTokenProvider( + token.WithPrivateKey(j.options.PublicKey), + token.WithPublicKey(j.options.PublicKey), + ) +} + +func (j *jwt) Options() auth.Options { + return j.options +} + +func (j *jwt) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) { + return nil, errors.New("JWT does not support Generate, use the Token method") +} + +func (j *jwt) Grant(role string, res *auth.Resource) error { + return errors.New("JWT does not support Grant") +} + +func (j *jwt) Revoke(role string, res *auth.Resource) error { + return errors.New("JWT does not support Revoke") +} + +func (j *jwt) Verify(acc *auth.Account, res *auth.Resource) error { + if acc == nil { + return auth.ErrForbidden + } + return nil +} + +func (j *jwt) Inspect(token string) (*auth.Account, error) { + return j.jwt.Inspect(token) +} + +func (j *jwt) Token(opts ...auth.TokenOption) (*auth.Token, error) { + options := auth.NewTokenOptions(opts...) + account := &auth.Account{ + ID: options.ID, + } + + tok, err := j.jwt.Generate(account, token.WithExpiry(options.Expiry)) + if err != nil { + return nil, err + } + + return &auth.Token{ + Created: tok.Created, + Expiry: tok.Expiry, + AccessToken: tok.Token, + }, nil +} diff --git a/config/cmd/cmd.go b/config/cmd/cmd.go index b5cd79f8..7cec8f99 100644 --- a/config/cmd/cmd.go +++ b/config/cmd/cmd.go @@ -70,6 +70,7 @@ import ( memTracer "github.com/micro/go-micro/v2/debug/trace/memory" // auth + jwtAuth "github.com/micro/go-micro/v2/auth/jwt" svcAuth "github.com/micro/go-micro/v2/auth/service" // auth providers @@ -369,6 +370,7 @@ var ( DefaultAuths = map[string]func(...auth.Option) auth.Auth{ "service": svcAuth.NewAuth, + "jwt": jwtAuth.NewAuth, } DefaultAuthProviders = map[string]func(...provider.Option) provider.Provider{