From 1a4f608ed139edf017e8be5591782eefffb543b7 Mon Sep 17 00:00:00 2001 From: mlboy Date: Tue, 10 Mar 2020 01:16:31 +0800 Subject: [PATCH] add: auth add generate options Expiry for set token expires (#1319) Co-authored-by: mlboy Co-authored-by: Asim Aslam --- auth/jwt/jwt.go | 3 +-- auth/options.go | 20 ++++++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/auth/jwt/jwt.go b/auth/jwt/jwt.go index b2aab0a8..49e1ff19 100644 --- a/auth/jwt/jwt.go +++ b/auth/jwt/jwt.go @@ -3,7 +3,6 @@ package jwt import ( "encoding/base64" "errors" - "time" "github.com/dgrijalva/jwt-go" "github.com/micro/go-micro/v2/auth" @@ -77,7 +76,7 @@ func (s *svc) Generate(id string, ops ...auth.GenerateOption) (*auth.Account, er account := jwt.NewWithClaims(jwt.SigningMethodRS256, AuthClaims{ id, options.Roles, options.Metadata, jwt.StandardClaims{ Subject: id, - ExpiresAt: time.Now().Add(time.Hour * 24).Unix(), + ExpiresAt: options.Expiry.Unix(), }, }) diff --git a/auth/options.go b/auth/options.go index 4f49d819..68b357b7 100644 --- a/auth/options.go +++ b/auth/options.go @@ -1,6 +1,10 @@ package auth -import "github.com/micro/go-micro/v2/auth/provider" +import ( + "time" + + "github.com/micro/go-micro/v2/auth/provider" +) type Options struct { // Token is an auth token @@ -66,6 +70,8 @@ type GenerateOptions struct { Metadata map[string]string // Roles/scopes associated with the account Roles []*Role + //Expiry of the token + Expiry time.Time } type GenerateOption func(o *GenerateOptions) @@ -84,12 +90,22 @@ func Roles(rs []*Role) func(o *GenerateOptions) { } } +// Expiry for the generated account's token expires +func Expiry(ex time.Time) func(o *GenerateOptions) { + return func(o *GenerateOptions) { + o.Expiry = ex + } +} + // NewGenerateOptions from a slice of options func NewGenerateOptions(opts ...GenerateOption) GenerateOptions { var options GenerateOptions for _, o := range opts { o(&options) } - + //set defualt expiry of token + if options.Expiry.IsZero() { + options.Expiry = time.Now().Add(time.Hour * 24) + } return options }