mirror of
https://github.com/labstack/echo.git
synced 2025-04-23 12:18:53 +02:00
Fix issue with JWT race (#968)
This commit is contained in:
parent
d79c13108c
commit
a5c75b002d
@ -141,7 +141,8 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
|
|||||||
if _, ok := config.Claims.(jwt.MapClaims); ok {
|
if _, ok := config.Claims.(jwt.MapClaims); ok {
|
||||||
token, err = jwt.Parse(auth, config.keyFunc)
|
token, err = jwt.Parse(auth, config.keyFunc)
|
||||||
} else {
|
} else {
|
||||||
claims := reflect.ValueOf(config.Claims).Interface().(jwt.Claims)
|
t := reflect.ValueOf(config.Claims).Type().Elem()
|
||||||
|
claims := reflect.New(t).Interface().(jwt.Claims)
|
||||||
token, err = jwt.ParseWithClaims(auth, claims, config.keyFunc)
|
token, err = jwt.ParseWithClaims(auth, claims, config.keyFunc)
|
||||||
}
|
}
|
||||||
if err == nil && token.Valid {
|
if err == nil && token.Valid {
|
||||||
|
@ -22,6 +22,42 @@ type jwtCustomClaims struct {
|
|||||||
jwtCustomInfo
|
jwtCustomInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestJWTRace(t *testing.T) {
|
||||||
|
e := echo.New()
|
||||||
|
handler := func(c echo.Context) error {
|
||||||
|
return c.String(http.StatusOK, "test")
|
||||||
|
}
|
||||||
|
initialToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
|
||||||
|
raceToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlJhY2UgQ29uZGl0aW9uIiwiYWRtaW4iOmZhbHNlfQ.Xzkx9mcgGqYMTkuxSCbJ67lsDyk5J2aB7hu65cEE-Ss"
|
||||||
|
validKey := []byte("secret")
|
||||||
|
|
||||||
|
h := JWTWithConfig(JWTConfig{
|
||||||
|
Claims: &jwtCustomClaims{},
|
||||||
|
SigningKey: validKey,
|
||||||
|
})(handler)
|
||||||
|
|
||||||
|
makeReq := func(token string) echo.Context {
|
||||||
|
req := httptest.NewRequest(echo.GET, "/", nil)
|
||||||
|
res := httptest.NewRecorder()
|
||||||
|
req.Header.Set(echo.HeaderAuthorization, DefaultJWTConfig.AuthScheme+" "+token)
|
||||||
|
c := e.NewContext(req, res)
|
||||||
|
assert.NoError(t, h(c))
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
c := makeReq(initialToken)
|
||||||
|
user := c.Get("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(*jwtCustomClaims)
|
||||||
|
assert.Equal(t, claims.Name, "John Doe")
|
||||||
|
|
||||||
|
makeReq(raceToken)
|
||||||
|
user = c.Get("user").(*jwt.Token)
|
||||||
|
claims = user.Claims.(*jwtCustomClaims)
|
||||||
|
// Initial context should still be "John Doe", not "Race Condition"
|
||||||
|
assert.Equal(t, claims.Name, "John Doe")
|
||||||
|
assert.Equal(t, claims.Admin, true)
|
||||||
|
}
|
||||||
|
|
||||||
func TestJWT(t *testing.T) {
|
func TestJWT(t *testing.T) {
|
||||||
e := echo.New()
|
e := echo.New()
|
||||||
handler := func(c echo.Context) error {
|
handler := func(c echo.Context) error {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user