1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-11-24 08:02:32 +02:00

add: auth add generate options Expiry for set token expires (#1319)

Co-authored-by: mlboy <ml3@meitu.com>
Co-authored-by: Asim Aslam <asim@aslam.me>
This commit is contained in:
mlboy 2020-03-10 01:16:31 +08:00 committed by GitHub
parent 43b0dbb123
commit 1a4f608ed1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 4 deletions

View File

@ -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(),
},
})

View File

@ -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
}