Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add ParseOptions field for HertzJWTMiddleware #13

Merged
merged 2 commits into from
Dec 25, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 27 additions & 15 deletions auth_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ package jwt
import (
"context"
"crypto/rsa"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
Expand Down Expand Up @@ -181,6 +182,9 @@ type HertzJWTMiddleware struct {

// CookieSameSite allow use protocol.CookieSameSite cookie param
CookieSameSite protocol.CookieSameSite

// ParseOptions allow to modify jwt's parser methods
ParseOptions []jwt.ParserOption
}

var (
Expand Down Expand Up @@ -447,19 +451,27 @@ func (mw *HertzJWTMiddleware) middlewareImpl(ctx context.Context, c *app.Request
return
}

if claims["exp"] == nil {
switch v := claims["exp"].(type) {
case nil:
mw.unauthorized(ctx, c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrMissingExpField, ctx, c))
return
}

if _, ok := claims["exp"].(float64); !ok {
mw.unauthorized(ctx, c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrWrongFormatOfExp, ctx, c))
return
}

if int64(claims["exp"].(float64)) < mw.TimeFunc().Unix() {
mw.unauthorized(ctx, c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, ctx, c))
return
case float64:
if int64(v) < mw.TimeFunc().Unix() {
mw.unauthorized(ctx, c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, ctx, c))
return
}
case json.Number:
n, err := v.Int64()
if err != nil {
mw.unauthorized(ctx, c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrWrongFormatOfExp, ctx, c))
return
}
if n < mw.TimeFunc().Unix() {
mw.unauthorized(ctx, c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, ctx, c))
return
}
default:
mw.Unauthorized(ctx, c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrWrongFormatOfExp, ctx, c))
}

c.Set("JWT_PAYLOAD", claims)
Expand Down Expand Up @@ -728,7 +740,7 @@ func (mw *HertzJWTMiddleware) ParseToken(ctx context.Context, c *app.RequestCont
}

if mw.KeyFunc != nil {
return jwt.Parse(token, mw.KeyFunc)
return jwt.Parse(token, mw.KeyFunc, mw.ParseOptions...)
}

return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
Expand All @@ -743,13 +755,13 @@ func (mw *HertzJWTMiddleware) ParseToken(ctx context.Context, c *app.RequestCont
c.Set("JWT_TOKEN", token)

return mw.Key, nil
})
}, mw.ParseOptions...)
}

// ParseTokenString parse jwt token string
func (mw *HertzJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error) {
if mw.KeyFunc != nil {
return jwt.Parse(token, mw.KeyFunc)
return jwt.Parse(token, mw.KeyFunc, mw.ParseOptions...)
}

return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
Expand All @@ -761,7 +773,7 @@ func (mw *HertzJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error)
}

return mw.Key, nil
})
}, mw.ParseOptions...)
}

func (mw *HertzJWTMiddleware) unauthorized(ctx context.Context, c *app.RequestContext, code int, message string) {
Expand Down
19 changes: 19 additions & 0 deletions auth_jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,25 @@ func TestAuthorizator(t *testing.T) {
assert.DeepEqual(t, http.StatusOK, w.Code)
}

func TestParseTokenWithJsonNumber(t *testing.T) {
authMiddleware, _ := New(&HertzJWTMiddleware{
li-jin-gou marked this conversation as resolved.
Show resolved Hide resolved
Realm: "test, zone",
Key: key,
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
Authenticator: defaultAuthenticator,
Unauthorized: func(ctx context.Context, c *app.RequestContext, code int, message string) {
c.String(code, message)
},
ParseOptions: []jwt.ParserOption{jwt.WithJSONNumber()},
})

handler := hertzHandler(authMiddleware)

w := ut.PerformRequest(handler, http.MethodGet, "/auth/hello", nil, ut.Header{Key: "Authorization", Value: "Bearer " + makeTokenString("HS256", "admin")})
assert.DeepEqual(t, http.StatusOK, w.Code)
}

func TestClaimsDuringAuthorization(t *testing.T) {
// the middleware to test
authMiddleware, _ := New(&HertzJWTMiddleware{
Expand Down