osg VerifyJWT 추가
This commit is contained in:
@ -9,6 +9,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@ -155,6 +156,49 @@ func (c *Client) MakeJWT(subject string, role string, ttl time.Duration) string
|
||||
return encoded + "." + string(sigenc)
|
||||
}
|
||||
|
||||
func (c *Client) VerifyJWT(token string) (subject string, role string) {
|
||||
dot := strings.LastIndex(token, ".")
|
||||
if dot < 0 {
|
||||
return
|
||||
}
|
||||
|
||||
encoded := token[:dot]
|
||||
sigenc := token[dot+1:]
|
||||
signature := make([]byte, encoding.DecodedLen(len(sigenc)))
|
||||
encoding.Decode(signature, []byte(sigenc))
|
||||
|
||||
mac := hmac.New(sha256.New, c.signingKey)
|
||||
mac.Write([]byte(encoded))
|
||||
calsig := mac.Sum(nil)
|
||||
if slices.Compare(calsig, signature) != 0 {
|
||||
return
|
||||
}
|
||||
|
||||
_, payload, ok := strings.Cut(encoded, ".")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
srcjson, err := encoding.DecodeString(payload)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var src struct {
|
||||
Exp int64 `json:"exp"`
|
||||
Sub string `json:"sub"`
|
||||
Roles string `json:"roles"`
|
||||
}
|
||||
if json.Unmarshal([]byte(srcjson), &src) != nil {
|
||||
return
|
||||
}
|
||||
if src.Exp < time.Now().Unix() {
|
||||
return
|
||||
}
|
||||
|
||||
return src.Sub, src.Roles
|
||||
}
|
||||
|
||||
func NewClient(cfg Config) (Client, error) {
|
||||
if len(cfg.Addresses) == 0 {
|
||||
return Client{}, nil
|
||||
|
||||
Reference in New Issue
Block a user