支持jwt

This commit is contained in:
白茶清欢 2023-08-10 17:30:49 +08:00
parent 0948cd51c0
commit 1019189ca7
4 changed files with 76 additions and 2 deletions

2
go.mod
View File

@ -4,4 +4,6 @@ go 1.20
require (
github.com/ddliu/go-httpclient v0.7.1
github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1
github.com/mssola/user_agent v0.6.0
)

8
go.sum
View File

@ -1,4 +1,8 @@
github.com/ddliu/go-httpclient v0.6.9 h1:/3hsBVpcgCJwqm1dkVlnAJ9NWuYInbRc+i9FyUXX/LE=
github.com/ddliu/go-httpclient v0.6.9/go.mod h1:zM9P0OxV4OGGz1pt/ibuj0ooX2SWH9a6MvXZLbT0JMc=
github.com/ddliu/go-httpclient v0.7.1 h1:COWYBalfbaFNe6e0eQU38++vCD5kzLh1H1RFs3xcn9g=
github.com/ddliu/go-httpclient v0.7.1/go.mod h1:uwipe9x9SYGk4JhBemO7+dD87QbiY224y0DLB9OY0Ik=
github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1 h1:CaO/zOnF8VvUfEbhRatPcwKVWamvbYd8tQGRWacE9kU=
github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1/go.mod h1:+hnT3ywWDTAFrW5aE+u2Sa/wT555ZqwoCS+pk3p6ry4=
github.com/mssola/user_agent v0.6.0 h1:uwPR4rtWlCHRFyyP9u2KOV0u8iQXmS7Z7feTrstQwk4=
github.com/mssola/user_agent v0.6.0/go.mod h1:TTPno8LPY3wAIEKRpAtkdMT0f8SE24pLRGPahjCH4uw=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@ -16,6 +16,8 @@ var (
IP *ip
// URL ...
URL *ownURL
// JWT ...
JWT *ownJwt
)
func init() {

66
util/jwt.go Normal file
View File

@ -0,0 +1,66 @@
// Package util ...
//
// Description : go-jwt具体实现
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2023-02-11 20:09
package util
import (
"errors"
"github.com/dgrijalva/jwt-go/v4"
)
type ownJwt struct {
}
type MyClaims struct {
jwt.StandardClaims
}
// Generate 生成 token
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 20:13 2023/2/11
func (j *ownJwt) Generate(signMethod jwt.SigningMethod, secret string, claims jwt.Claims) (string, error) {
if nil == signMethod {
signMethod = jwt.SigningMethodHS256
}
var (
token *jwt.Token
)
if nil == claims {
token = jwt.New(signMethod)
} else {
token = jwt.NewWithClaims(signMethod, claims)
}
return token.SignedString([]byte(secret))
}
// Validate 验证token
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 20:13 2023/2/11
func (j *ownJwt) Validate(inputToken string, secret string, claims jwt.Claims) (jwt.Claims, error) {
var (
token *jwt.Token
err error
)
if token, err = jwt.ParseWithClaims(inputToken, claims, func(tokenInfo *jwt.Token) (interface{}, error) {
return []byte(secret), nil
}); nil != err {
return nil, errors.New("token parse fail : " + err.Error())
}
if !token.Valid {
return nil, errors.New("token is valid : " + err.Error())
}
return token.Claims, nil
}