Skip to content

Commit

Permalink
调整JWT的ID,Issuer,使得可以携带更多信息
Browse files Browse the repository at this point in the history
  • Loading branch information
gowater committed Nov 23, 2023
1 parent cb5f12c commit 64632d6
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"time"
)

func SetAuthToken(uniqueUser, privateKeyPath string, expire time.Duration) (tokenString string, err error) {
func SetAuthToken(uniqueUser, issuer, privateKeyPath string, expire time.Duration) (tokenString string, err error) {
privateKey, err := os.ReadFile(privateKeyPath)
if err != nil {
return "", err
Expand All @@ -21,7 +21,8 @@ func SetAuthToken(uniqueUser, privateKeyPath string, expire time.Duration) (toke
}

claims := jwt.RegisteredClaims{
Issuer: uniqueUser,
ID: uniqueUser,
Issuer: issuer,
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expire)),
}

Expand All @@ -40,7 +41,7 @@ func SetAuthToken(uniqueUser, privateKeyPath string, expire time.Duration) (toke
}

// ParseFromRequest 兼容 http,ws
func ParseFromRequest(req *http.Request, publicKeyPath string) (uniqueUser, signature string, err error) {
func ParseFromRequest(req *http.Request, publicKeyPath string) (uniqueUser, issuer, signature string, err error) {
token, err := request.ParseFromRequest(req, request.AuthorizationHeaderExtractor, func(t *jwt.Token) (any, error) {
publicKey, innErr := os.ReadFile(publicKeyPath)
if innErr != nil {
Expand All @@ -65,22 +66,22 @@ func ParseFromRequest(req *http.Request, publicKeyPath string) (uniqueUser, sign
return jwt.ParseRSAPublicKeyFromPEM(publicKey)
})
if err != nil {
return "", "", err
return "", "", "", err
}

if token.Valid {
return parseToken(token)
}
}

return "", "", jwt.ErrTokenSignatureInvalid
return "", "", "", jwt.ErrTokenSignatureInvalid
}

func parseToken(token *jwt.Token) (uniqueUser, signature string, err error) {
func parseToken(token *jwt.Token) (uniqueUser, issuer, signature string, err error) {
claims, ok := token.Claims.(*jwt.RegisteredClaims)
if !ok {
return "", "", jwt.ErrTokenInvalidClaims
return "", "", "", jwt.ErrTokenInvalidClaims
}

return claims.Issuer, token.Signature, nil
return claims.ID, claims.Issuer, token.Signature, nil
}

0 comments on commit 64632d6

Please sign in to comment.