1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
token.go 4.28 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-11-22 16:57 . jwt,支持原始数据,不需要base64
package jwt
import (
"encoding/base64"
"fmt"
"gitee.com/h79/goutils/auth/token"
"gitee.com/h79/goutils/common/result"
"gitee.com/h79/goutils/common/timer"
"github.com/dgrijalva/jwt-go"
)
// 保证 Token struct implement token.Token
var _ token.Token = (*Token)(nil)
type Token struct {
token.Session
Token string `json:"token"`
Extend string `json:"-"`
source jwtSource `json:"-"`
key token.Key `json:"-"`
base64 bool `json:"-"`
}
func NewToken(key token.Key, base64 bool) *Token {
return &Token{
key: key,
base64: base64,
}
}
func (tk *Token) WithSource(source token.Source) token.Token {
tk.source.AppId = source.AppId
tk.source.Source = source.Source
return tk
}
// WithSession token.Token interface
func (tk *Token) WithSession(session token.Session) token.Token {
tk.Session = session
return tk
}
// WithExtend token.Token interface
func (tk *Token) WithExtend(extend string) token.Token {
tk.Extend = extend
return tk
}
// GetSession token.Token interface
func (tk *Token) GetSession() token.Session {
return tk.Session
}
// GetExtend token.Token interface
func (tk *Token) GetExtend() string {
return tk.Extend
}
// GetToken token.Token interface
func (tk *Token) GetToken() string {
return tk.Token
}
// Update token.Token interface
func (tk *Token) Update() (string, error) {
expire := timer.NowExpireWithSecond(tk.key.ExpireIn())
jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwtClaims{
StandardClaims: jwt.StandardClaims{
Subject: tk.Uid,
IssuedAt: expire.StartIn,
ExpiresAt: expire.ExpireIn,
},
Source: tk.source,
Session: tk.Session.UserToken,
Extend: tk.Extend,
})
tStr, err := jwtToken.SignedString(tk.key.Key())
if err != nil {
return "", err
}
if tk.base64 {
tk.Token = base64.StdEncoding.EncodeToString([]byte(tStr))
} else {
tk.Token = tStr
}
return tk.Token, nil
}
// DecodeToken 不需要认证,解包里面的信息
func DecodeToken(tk string) (token.Token, error) {
bytes, er := base64.StdEncoding.DecodeString(tk)
if er != nil {
return nil, er
}
return DecodeTokenNoBase64(string(bytes))
}
func DecodeTokenNoBase64(tk string) (token.Token, error) {
// for 读取信息,不验证
tc := jwtClaims{}
_, jwtEr := jwt.ParseWithClaims(tk, &tc, nil)
err, ok := jwtEr.(*jwt.ValidationError)
if !ok {
return nil, jwtEr
}
if err.Errors != jwt.ValidationErrorUnverifiable {
return nil, jwtEr
}
return tc.To(tk), nil
}
// VerifyToken 需要认证,解包里面的信息
func VerifyToken(tk string, key token.Key) (token.Token, error) {
bytes, er := base64.StdEncoding.DecodeString(tk)
if er != nil {
return nil, er
}
return VerifyTokenNoBase64(string(bytes), key)
}
func VerifyTokenNoBase64(tk string, key token.Key) (token.Token, error) {
tc := jwtClaims{}
_, jwtEr := jwt.ParseWithClaims(tk, &tc, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return key.Key(), nil
})
errStr := ""
code := result.ErrOk
if err, ok := jwtEr.(*jwt.ValidationError); ok {
code = result.ErrToken
if err.Errors&jwt.ValidationErrorMalformed != 0 {
// Token is malformed
code |= result.TokenMalformed
} else if err.Errors&jwt.ValidationErrorUnverifiable != 0 {
// Token could not be verified because of signing problems
code |= result.TokenUnVerify
} else if err.Errors&jwt.ValidationErrorSignatureInvalid != 0 {
// Signature validation failed
code |= result.TokenSigned
} else if err.Errors&jwt.ValidationErrorExpired != 0 {
code |= result.TokenExpired
} else {
code |= result.TokenOther
}
errStr = err.Error()
}
tok := tc.To(tk)
tok.key = key
if code == result.ErrOk {
return tok, nil
}
return tok, result.Error(code, errStr)
}
type jwtClaims struct {
jwt.StandardClaims
Source jwtSource `json:"source"`
Session string `json:"session"`
Extend string `json:"extend"`
}
type jwtSource struct {
AppId string `json:"appid"`
Source string `json:"source"`
}
// Valid type Claims.interface
func (tc *jwtClaims) Valid() error {
return nil
}
func (tc *jwtClaims) To(tk string) *Token {
return &Token{
Session: token.CreateSession(tc.StandardClaims.Subject, tc.Session),
Token: tk,
Extend: tc.Extend,
source: tc.Source,
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.2.21

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385