Skip to content

Commit

Permalink
支持 WebSocket 验证
Browse files Browse the repository at this point in the history
  • Loading branch information
gowater committed Jul 4, 2023
1 parent ce5e826 commit bbb9c1d
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func SetAuthToken(uniqueUser, privateKeyPath string, expire time.Duration) (toke
return tokenString, nil
}

func ParseAndValid(req *http.Request, publicKeyPath string) (uniqueUser, signature string, err error) {
func ParseFromRequest(req *http.Request, publicKeyPath string) (uniqueUser, signature string, err error) {
token, err := request.ParseFromRequest(req, request.AuthorizationHeaderExtractor, func(t *jwt.Token) (interface{}, error) {
publicKey, innErr := os.ReadFile(publicKeyPath)
if innErr != nil {
Expand All @@ -52,7 +52,9 @@ func ParseAndValid(req *http.Request, publicKeyPath string) (uniqueUser, signatu
return "", "", err
}

if !token.Valid {
wsp := req.Header.Get("Sec-Websocket-Protocol")

if !token.Valid && len(wsp) > 0 {
return "", "", jwt.ErrTokenSignatureInvalid
}

Expand All @@ -63,3 +65,38 @@ func ParseAndValid(req *http.Request, publicKeyPath string) (uniqueUser, signatu

return claims.Issuer, token.Signature, nil
}

func ParseWithClaims(req *http.Request, publicKeyPath string) (uniqueUser, signature string, err error) {
wsp := req.Header.Get("Sec-Websocket-Protocol")
if len(wsp) > 0 {
token, er := jwt.ParseWithClaims(wsp, &jwt.RegisteredClaims{}, func(t *jwt.Token) (interface{}, error) {
publicKey, innErr := os.ReadFile(publicKeyPath)
if innErr != nil {
return "", innErr
}

return jwt.ParseRSAPublicKeyFromPEM(publicKey)
})
if er != nil {
return "", "", er
}

if !token.Valid && len(wsp) > 0 {
return "", "", jwt.ErrTokenSignatureInvalid
}

claims, ok := token.Claims.(*jwt.RegisteredClaims)
if !ok {
return "", "", jwt.ErrTokenInvalidClaims
}

//issuer, er := claims.GetIssuer()
//if er != nil {
// return "", "", er
//}

return claims.Issuer, token.Signature, nil
}

return "", "", nil
}

0 comments on commit bbb9c1d

Please sign in to comment.