2015-05-12 00:43:54 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2021-05-08 21:19:24 +02:00
|
|
|
"errors"
|
2021-06-06 20:36:41 +02:00
|
|
|
"fmt"
|
2015-05-12 00:43:54 +02:00
|
|
|
"net/http"
|
2016-09-23 07:53:44 +02:00
|
|
|
"net/http/httptest"
|
2020-12-01 08:51:20 +02:00
|
|
|
"net/url"
|
|
|
|
"strings"
|
2015-05-12 00:43:54 +02:00
|
|
|
"testing"
|
2015-05-18 07:54:29 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
"github.com/golang-jwt/jwt/v4"
|
2019-01-30 12:56:56 +02:00
|
|
|
"github.com/labstack/echo/v4"
|
2015-05-30 19:54:55 +02:00
|
|
|
"github.com/stretchr/testify/assert"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
func createTestParseTokenFuncForJWTGo(signingMethod string, signingKey interface{}) func(c echo.Context, auth string) (interface{}, error) {
|
|
|
|
// This is minimal implementation for github.com/golang-jwt/jwt as JWT parser library. good enough to get old tests running
|
|
|
|
keyFunc := func(t *jwt.Token) (interface{}, error) {
|
|
|
|
if t.Method.Alg() != signingMethod {
|
|
|
|
return nil, fmt.Errorf("unexpected jwt signing method=%v", t.Header["alg"])
|
|
|
|
}
|
|
|
|
return signingKey, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return func(c echo.Context, auth string) (interface{}, error) {
|
|
|
|
token, err := jwt.ParseWithClaims(auth, jwt.MapClaims{}, keyFunc)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if !token.Valid {
|
|
|
|
return nil, errors.New("invalid token")
|
|
|
|
}
|
|
|
|
return token, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-20 18:12:17 +02:00
|
|
|
// jwtCustomInfo defines some custom types we're going to use within our tokens.
|
|
|
|
type jwtCustomInfo struct {
|
2016-08-20 17:59:36 +02:00
|
|
|
Name string `json:"name"`
|
|
|
|
Admin bool `json:"admin"`
|
|
|
|
}
|
|
|
|
|
2016-08-20 18:12:17 +02:00
|
|
|
// jwtCustomClaims are custom claims expanding default ones.
|
|
|
|
type jwtCustomClaims struct {
|
2016-08-20 17:59:36 +02:00
|
|
|
*jwt.StandardClaims
|
2016-08-20 18:12:17 +02:00
|
|
|
jwtCustomInfo
|
2016-08-20 17:59:36 +02:00
|
|
|
}
|
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
func TestJWT_combinations(t *testing.T) {
|
2016-04-25 19:58:11 +02:00
|
|
|
e := echo.New()
|
|
|
|
handler := func(c echo.Context) error {
|
|
|
|
return c.String(http.StatusOK, "test")
|
|
|
|
}
|
|
|
|
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
|
2016-07-02 00:07:40 +02:00
|
|
|
validKey := []byte("secret")
|
|
|
|
invalidKey := []byte("invalid-key")
|
2021-07-15 22:34:01 +02:00
|
|
|
validAuth := "Bearer " + token
|
2016-04-25 19:58:11 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
var testCases = []struct {
|
|
|
|
name string
|
2016-07-02 00:07:40 +02:00
|
|
|
config JWTConfig
|
|
|
|
reqURL string // "/" if empty
|
|
|
|
hdrAuth string
|
2016-07-02 11:26:05 +02:00
|
|
|
hdrCookie string // test.Request doesn't provide SetCookie(); use name=val
|
2020-12-01 08:51:20 +02:00
|
|
|
formValues map[string]string
|
2021-07-15 22:34:01 +02:00
|
|
|
expPanic bool
|
|
|
|
expErrCode int // 0 for Success
|
2016-07-02 00:07:40 +02:00
|
|
|
}{
|
2016-08-27 22:03:40 +02:00
|
|
|
{
|
|
|
|
expPanic: true,
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "No signing key provided",
|
2016-08-27 22:03:40 +02:00
|
|
|
},
|
2016-07-02 00:07:40 +02:00
|
|
|
{
|
2021-07-15 22:34:01 +02:00
|
|
|
expErrCode: http.StatusUnauthorized,
|
|
|
|
hdrAuth: validAuth,
|
2016-07-02 00:07:40 +02:00
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo("RS256", validKey),
|
2016-07-02 00:07:40 +02:00
|
|
|
},
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Unexpected signing method",
|
2016-07-02 00:07:40 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
expErrCode: http.StatusUnauthorized,
|
|
|
|
hdrAuth: validAuth,
|
2021-07-15 22:34:01 +02:00
|
|
|
config: JWTConfig{
|
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, invalidKey),
|
|
|
|
},
|
|
|
|
name: "Invalid key",
|
2016-07-02 00:07:40 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
hdrAuth: validAuth,
|
2021-07-15 22:34:01 +02:00
|
|
|
config: JWTConfig{
|
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
},
|
|
|
|
name: "Valid JWT",
|
2016-07-02 00:07:40 +02:00
|
|
|
},
|
2016-12-18 12:38:46 +02:00
|
|
|
{
|
|
|
|
hdrAuth: "Token" + " " + token,
|
2021-07-15 22:34:01 +02:00
|
|
|
config: JWTConfig{
|
|
|
|
TokenLookup: "header:" + echo.HeaderAuthorization + ":Token ",
|
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
},
|
|
|
|
name: "Valid JWT with custom AuthScheme",
|
2016-12-18 12:38:46 +02:00
|
|
|
},
|
2016-08-27 19:52:35 +02:00
|
|
|
{
|
|
|
|
hdrAuth: validAuth,
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, []byte("secret")),
|
2016-08-27 19:52:35 +02:00
|
|
|
},
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Valid JWT with custom claims",
|
2016-08-27 19:52:35 +02:00
|
|
|
},
|
2016-07-02 00:07:40 +02:00
|
|
|
{
|
|
|
|
hdrAuth: "invalid-auth",
|
2021-07-15 22:34:01 +02:00
|
|
|
expErrCode: http.StatusUnauthorized,
|
|
|
|
config: JWTConfig{
|
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
},
|
|
|
|
name: "Invalid Authorization header",
|
2016-07-02 00:07:40 +02:00
|
|
|
},
|
|
|
|
{
|
2021-07-15 22:34:01 +02:00
|
|
|
config: JWTConfig{
|
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
},
|
|
|
|
expErrCode: http.StatusUnauthorized,
|
|
|
|
name: "Empty header auth field",
|
2016-07-02 00:07:40 +02:00
|
|
|
},
|
2016-07-02 00:27:48 +02:00
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "query:jwt",
|
2016-07-02 00:27:48 +02:00
|
|
|
},
|
|
|
|
reqURL: "/?a=b&jwt=" + token,
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Valid query method",
|
2016-07-02 00:27:48 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "query:jwt",
|
2016-07-02 00:27:48 +02:00
|
|
|
},
|
|
|
|
reqURL: "/?a=b&jwtxyz=" + token,
|
2021-07-15 22:34:01 +02:00
|
|
|
expErrCode: http.StatusUnauthorized,
|
|
|
|
name: "Invalid query param name",
|
2016-07-02 00:27:48 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "query:jwt",
|
2016-07-02 00:27:48 +02:00
|
|
|
},
|
|
|
|
reqURL: "/?a=b&jwt=invalid-token",
|
|
|
|
expErrCode: http.StatusUnauthorized,
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Invalid query param value",
|
2016-07-02 00:27:48 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "query:jwt",
|
2016-07-02 00:27:48 +02:00
|
|
|
},
|
|
|
|
reqURL: "/?a=b",
|
2021-07-15 22:34:01 +02:00
|
|
|
expErrCode: http.StatusUnauthorized,
|
|
|
|
name: "Empty query",
|
2016-07-02 00:27:48 +02:00
|
|
|
},
|
2019-06-09 18:49:52 +02:00
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "param:jwt",
|
2019-06-09 18:49:52 +02:00
|
|
|
},
|
|
|
|
reqURL: "/" + token,
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Valid param method",
|
2019-06-09 18:49:52 +02:00
|
|
|
},
|
2016-07-02 11:26:05 +02:00
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "cookie:jwt",
|
2016-07-02 11:26:05 +02:00
|
|
|
},
|
|
|
|
hdrCookie: "jwt=" + token,
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Valid cookie method",
|
2016-07-02 11:26:05 +02:00
|
|
|
},
|
2021-05-08 21:30:06 +02:00
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "query:jwt,cookie:jwt",
|
2021-05-08 21:30:06 +02:00
|
|
|
},
|
|
|
|
hdrCookie: "jwt=" + token,
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Multiple jwt lookuop",
|
2021-05-08 21:30:06 +02:00
|
|
|
},
|
2016-07-02 11:26:05 +02:00
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "cookie:jwt",
|
2016-07-02 11:26:05 +02:00
|
|
|
},
|
|
|
|
expErrCode: http.StatusUnauthorized,
|
|
|
|
hdrCookie: "jwt=invalid",
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Invalid token with cookie method",
|
2016-07-02 11:26:05 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "cookie:jwt",
|
2016-07-02 11:26:05 +02:00
|
|
|
},
|
2021-07-15 22:34:01 +02:00
|
|
|
expErrCode: http.StatusUnauthorized,
|
|
|
|
name: "Empty cookie",
|
2016-07-02 11:26:05 +02:00
|
|
|
},
|
2020-12-01 08:51:20 +02:00
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "form:jwt",
|
2020-12-01 08:51:20 +02:00
|
|
|
},
|
|
|
|
formValues: map[string]string{"jwt": token},
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Valid form method",
|
2020-12-01 08:51:20 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "form:jwt",
|
2020-12-01 08:51:20 +02:00
|
|
|
},
|
|
|
|
expErrCode: http.StatusUnauthorized,
|
|
|
|
formValues: map[string]string{"jwt": "invalid"},
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Invalid token with form method",
|
2020-12-01 08:51:20 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
config: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, validKey),
|
|
|
|
TokenLookup: "form:jwt",
|
2021-05-08 21:19:24 +02:00
|
|
|
},
|
|
|
|
expErrCode: http.StatusUnauthorized,
|
2021-07-15 22:34:01 +02:00
|
|
|
name: "Empty form field",
|
2021-05-08 21:19:24 +02:00
|
|
|
},
|
2021-07-15 22:34:01 +02:00
|
|
|
}
|
2016-04-25 19:58:11 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
for _, tc := range testCases {
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
if tc.reqURL == "" {
|
|
|
|
tc.reqURL = "/"
|
2020-12-01 08:51:20 +02:00
|
|
|
}
|
2019-06-09 18:49:52 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
var req *http.Request
|
|
|
|
if len(tc.formValues) > 0 {
|
|
|
|
form := url.Values{}
|
|
|
|
for k, v := range tc.formValues {
|
|
|
|
form.Set(k, v)
|
|
|
|
}
|
|
|
|
req = httptest.NewRequest(http.MethodPost, tc.reqURL, strings.NewReader(form.Encode()))
|
|
|
|
req.Header.Set(echo.HeaderContentType, "application/x-www-form-urlencoded")
|
|
|
|
req.ParseForm()
|
|
|
|
} else {
|
|
|
|
req = httptest.NewRequest(http.MethodGet, tc.reqURL, nil)
|
|
|
|
}
|
|
|
|
res := httptest.NewRecorder()
|
|
|
|
req.Header.Set(echo.HeaderAuthorization, tc.hdrAuth)
|
|
|
|
req.Header.Set(echo.HeaderCookie, tc.hdrCookie)
|
|
|
|
c := e.NewContext(req, res)
|
|
|
|
|
|
|
|
if tc.reqURL == "/"+token {
|
|
|
|
cc := c.(echo.EditableContext)
|
|
|
|
cc.SetPathParams(echo.PathParams{
|
|
|
|
{Name: "jwt", Value: token},
|
|
|
|
})
|
2016-08-27 19:52:35 +02:00
|
|
|
}
|
2019-05-17 16:45:49 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
if tc.expPanic {
|
|
|
|
assert.Panics(t, func() {
|
|
|
|
JWTWithConfig(tc.config)
|
|
|
|
}, tc.name)
|
|
|
|
return
|
|
|
|
}
|
2019-05-17 16:45:49 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
if tc.expErrCode != 0 {
|
|
|
|
h := JWTWithConfig(tc.config)(handler)
|
|
|
|
he := h(c).(*echo.HTTPError)
|
|
|
|
assert.Equal(t, tc.expErrCode, he.Code)
|
|
|
|
return
|
|
|
|
}
|
2019-05-17 16:45:49 +02:00
|
|
|
|
|
|
|
h := JWTWithConfig(tc.config)(handler)
|
2021-07-15 22:34:01 +02:00
|
|
|
if assert.NoError(t, h(c), tc.name) {
|
|
|
|
user := c.Get("user").(*jwt.Token)
|
|
|
|
switch claims := user.Claims.(type) {
|
|
|
|
case jwt.MapClaims:
|
|
|
|
assert.Equal(t, claims["name"], "John Doe")
|
|
|
|
case *jwtCustomClaims:
|
|
|
|
assert.Equal(t, claims.Name, "John Doe")
|
|
|
|
assert.Equal(t, claims.Admin, true)
|
|
|
|
default:
|
|
|
|
panic("unexpected type of claims")
|
|
|
|
}
|
2019-05-17 16:45:49 +02:00
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
})
|
2019-05-17 16:45:49 +02:00
|
|
|
}
|
|
|
|
}
|
2021-06-06 20:36:41 +02:00
|
|
|
|
|
|
|
func TestJWTConfig_skipper(t *testing.T) {
|
|
|
|
e := echo.New()
|
|
|
|
|
|
|
|
e.Use(JWTWithConfig(JWTConfig{
|
|
|
|
Skipper: func(context echo.Context) bool {
|
|
|
|
return true // skip everything
|
|
|
|
},
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, []byte("secret")),
|
2021-06-06 20:36:41 +02:00
|
|
|
}))
|
|
|
|
|
|
|
|
isCalled := false
|
|
|
|
e.GET("/", func(c echo.Context) error {
|
|
|
|
isCalled = true
|
|
|
|
return c.String(http.StatusTeapot, "test")
|
|
|
|
})
|
|
|
|
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
|
|
res := httptest.NewRecorder()
|
|
|
|
e.ServeHTTP(res, req)
|
|
|
|
|
|
|
|
assert.Equal(t, http.StatusTeapot, res.Code)
|
|
|
|
assert.True(t, isCalled)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestJWTConfig_BeforeFunc(t *testing.T) {
|
|
|
|
e := echo.New()
|
|
|
|
e.GET("/", func(c echo.Context) error {
|
|
|
|
return c.String(http.StatusTeapot, "test")
|
|
|
|
})
|
|
|
|
|
|
|
|
isCalled := false
|
|
|
|
e.Use(JWTWithConfig(JWTConfig{
|
|
|
|
BeforeFunc: func(context echo.Context) {
|
|
|
|
isCalled = true
|
|
|
|
},
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, []byte("secret")),
|
2021-06-06 20:36:41 +02:00
|
|
|
}))
|
|
|
|
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
2021-07-15 22:34:01 +02:00
|
|
|
req.Header.Set(echo.HeaderAuthorization, "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ")
|
2021-06-06 20:36:41 +02:00
|
|
|
res := httptest.NewRecorder()
|
|
|
|
e.ServeHTTP(res, req)
|
|
|
|
|
|
|
|
assert.Equal(t, http.StatusTeapot, res.Code)
|
|
|
|
assert.True(t, isCalled)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestJWTConfig_extractorErrorHandling(t *testing.T) {
|
|
|
|
var testCases = []struct {
|
|
|
|
name string
|
|
|
|
given JWTConfig
|
|
|
|
expectStatusCode int
|
|
|
|
}{
|
|
|
|
{
|
|
|
|
name: "ok, ErrorHandler is executed",
|
|
|
|
given: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, []byte("secret")),
|
|
|
|
ErrorHandler: func(c echo.Context, err error) error {
|
2021-06-06 20:36:41 +02:00
|
|
|
return echo.NewHTTPError(http.StatusTeapot, "custom_error")
|
|
|
|
},
|
|
|
|
},
|
|
|
|
expectStatusCode: http.StatusTeapot,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, tc := range testCases {
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
e := echo.New()
|
|
|
|
e.GET("/", func(c echo.Context) error {
|
|
|
|
return c.String(http.StatusNotImplemented, "should not end up here")
|
|
|
|
})
|
|
|
|
|
|
|
|
e.Use(JWTWithConfig(tc.given))
|
|
|
|
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
|
|
res := httptest.NewRecorder()
|
|
|
|
e.ServeHTTP(res, req)
|
|
|
|
|
|
|
|
assert.Equal(t, tc.expectStatusCode, res.Code)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestJWTConfig_parseTokenErrorHandling(t *testing.T) {
|
|
|
|
var testCases = []struct {
|
|
|
|
name string
|
|
|
|
given JWTConfig
|
|
|
|
expectErr string
|
|
|
|
}{
|
|
|
|
{
|
|
|
|
name: "ok, ErrorHandler is executed",
|
|
|
|
given: JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: createTestParseTokenFuncForJWTGo(AlgorithmHS256, []byte("secret")),
|
|
|
|
ErrorHandler: func(c echo.Context, err error) error {
|
2021-06-06 20:36:41 +02:00
|
|
|
return echo.NewHTTPError(http.StatusTeapot, "ErrorHandler: "+err.Error())
|
|
|
|
},
|
|
|
|
},
|
|
|
|
expectErr: "{\"message\":\"ErrorHandler: parsing failed\"}\n",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, tc := range testCases {
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
e := echo.New()
|
|
|
|
//e.Debug = true
|
|
|
|
e.GET("/", func(c echo.Context) error {
|
|
|
|
return c.String(http.StatusNotImplemented, "should not end up here")
|
|
|
|
})
|
|
|
|
|
|
|
|
config := tc.given
|
|
|
|
parseTokenCalled := false
|
2021-07-15 22:34:01 +02:00
|
|
|
config.ParseTokenFunc = func(c echo.Context, auth string) (interface{}, error) {
|
2021-06-06 20:36:41 +02:00
|
|
|
parseTokenCalled = true
|
|
|
|
return nil, errors.New("parsing failed")
|
|
|
|
}
|
|
|
|
e.Use(JWTWithConfig(config))
|
|
|
|
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
2021-07-15 22:34:01 +02:00
|
|
|
req.Header.Set(echo.HeaderAuthorization, "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ")
|
2021-06-06 20:36:41 +02:00
|
|
|
res := httptest.NewRecorder()
|
|
|
|
|
|
|
|
e.ServeHTTP(res, req)
|
|
|
|
|
|
|
|
assert.Equal(t, http.StatusTeapot, res.Code)
|
|
|
|
assert.Equal(t, tc.expectErr, res.Body.String())
|
|
|
|
assert.True(t, parseTokenCalled)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestJWTConfig_custom_ParseTokenFunc_Keyfunc(t *testing.T) {
|
|
|
|
e := echo.New()
|
|
|
|
e.GET("/", func(c echo.Context) error {
|
|
|
|
return c.String(http.StatusTeapot, "test")
|
|
|
|
})
|
|
|
|
|
2021-08-01 10:12:23 +02:00
|
|
|
// example of minimal custom ParseTokenFunc implementation. Allows you to use different versions of `github.com/golang-jwt/jwt`
|
2021-06-06 20:36:41 +02:00
|
|
|
// with current JWT middleware
|
|
|
|
signingKey := []byte("secret")
|
|
|
|
|
|
|
|
config := JWTConfig{
|
2021-07-15 22:34:01 +02:00
|
|
|
ParseTokenFunc: func(c echo.Context, auth string) (interface{}, error) {
|
2021-06-06 20:36:41 +02:00
|
|
|
keyFunc := func(t *jwt.Token) (interface{}, error) {
|
|
|
|
if t.Method.Alg() != "HS256" {
|
|
|
|
return nil, fmt.Errorf("unexpected jwt signing method=%v", t.Header["alg"])
|
|
|
|
}
|
|
|
|
return signingKey, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// claims are of type `jwt.MapClaims` when token is created with `jwt.Parse`
|
|
|
|
token, err := jwt.Parse(auth, keyFunc)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if !token.Valid {
|
|
|
|
return nil, errors.New("invalid token")
|
|
|
|
}
|
|
|
|
return token, nil
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
e.Use(JWTWithConfig(config))
|
|
|
|
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
2021-07-15 22:34:01 +02:00
|
|
|
req.Header.Set(echo.HeaderAuthorization, "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ")
|
2021-06-06 20:36:41 +02:00
|
|
|
res := httptest.NewRecorder()
|
|
|
|
e.ServeHTTP(res, req)
|
|
|
|
|
|
|
|
assert.Equal(t, http.StatusTeapot, res.Code)
|
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
|
|
|
|
func TestMustJWTWithConfig_SuccessHandler(t *testing.T) {
|
|
|
|
e := echo.New()
|
|
|
|
|
|
|
|
e.GET("/", func(c echo.Context) error {
|
|
|
|
success := c.Get("success").(string)
|
|
|
|
user := c.Get("user").(string)
|
|
|
|
return c.String(http.StatusTeapot, fmt.Sprintf("%v:%v", success, user))
|
|
|
|
})
|
|
|
|
|
|
|
|
mw, err := JWTConfig{
|
|
|
|
ParseTokenFunc: func(c echo.Context, auth string) (interface{}, error) {
|
|
|
|
return auth, nil
|
|
|
|
},
|
|
|
|
SuccessHandler: func(c echo.Context) {
|
|
|
|
c.Set("success", "yes")
|
|
|
|
},
|
|
|
|
}.ToMiddleware()
|
|
|
|
assert.NoError(t, err)
|
|
|
|
e.Use(mw)
|
|
|
|
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
|
|
req.Header.Add(echo.HeaderAuthorization, "Bearer valid_token_base64")
|
|
|
|
res := httptest.NewRecorder()
|
|
|
|
e.ServeHTTP(res, req)
|
|
|
|
|
|
|
|
assert.Equal(t, "yes:valid_token_base64", res.Body.String())
|
|
|
|
assert.Equal(t, http.StatusTeapot, res.Code)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestJWTWithConfig_CallNextOnNilErrorHandlerResult(t *testing.T) {
|
|
|
|
var testCases = []struct {
|
|
|
|
name string
|
|
|
|
givenCallNext bool
|
|
|
|
givenErrorHandler JWTErrorHandlerWithContext
|
|
|
|
givenTokenLookup string
|
|
|
|
whenAuthHeaders []string
|
|
|
|
whenCookies []string
|
|
|
|
whenParseReturn string
|
|
|
|
whenParseError error
|
|
|
|
expectHandlerCalled bool
|
|
|
|
expect string
|
|
|
|
expectCode int
|
|
|
|
}{
|
|
|
|
{
|
|
|
|
name: "ok, with valid JWT from auth header",
|
|
|
|
givenCallNext: true,
|
|
|
|
givenErrorHandler: func(c echo.Context, err error) error {
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
whenAuthHeaders: []string{"Bearer valid_token_base64"},
|
|
|
|
whenParseReturn: "valid_token",
|
|
|
|
expectCode: http.StatusTeapot,
|
|
|
|
expect: "valid_token",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "ok, missing header, callNext and set public_token from error handler",
|
|
|
|
givenCallNext: true,
|
|
|
|
givenErrorHandler: func(c echo.Context, err error) error {
|
|
|
|
if err != ErrJWTMissing {
|
|
|
|
panic("must get ErrJWTMissing")
|
|
|
|
}
|
|
|
|
c.Set("user", "public_token")
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
whenAuthHeaders: []string{}, // no JWT header
|
|
|
|
expectCode: http.StatusTeapot,
|
|
|
|
expect: "public_token",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "ok, invalid token, callNext and set public_token from error handler",
|
|
|
|
givenCallNext: true,
|
|
|
|
givenErrorHandler: func(c echo.Context, err error) error {
|
|
|
|
// this is probably not realistic usecase. on parse error you probably want to return error
|
|
|
|
if err.Error() != "parser_error" {
|
|
|
|
panic("must get parser_error")
|
|
|
|
}
|
|
|
|
c.Set("user", "public_token")
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
whenAuthHeaders: []string{"Bearer invalid_header"},
|
|
|
|
whenParseError: errors.New("parser_error"),
|
|
|
|
expectCode: http.StatusTeapot,
|
|
|
|
expect: "public_token",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "nok, invalid token, return error from error handler",
|
|
|
|
givenCallNext: true,
|
|
|
|
givenErrorHandler: func(c echo.Context, err error) error {
|
|
|
|
if err.Error() != "parser_error" {
|
|
|
|
panic("must get parser_error")
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
},
|
|
|
|
whenAuthHeaders: []string{"Bearer invalid_header"},
|
|
|
|
whenParseError: errors.New("parser_error"),
|
|
|
|
expectCode: http.StatusInternalServerError,
|
|
|
|
expect: "{\"message\":\"Internal Server Error\"}\n",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "nok, callNext but return error from error handler",
|
|
|
|
givenCallNext: true,
|
|
|
|
givenErrorHandler: func(c echo.Context, err error) error {
|
|
|
|
return err
|
|
|
|
},
|
|
|
|
whenAuthHeaders: []string{}, // no JWT header
|
|
|
|
expectCode: http.StatusUnauthorized,
|
|
|
|
expect: "{\"message\":\"missing or malformed jwt\"}\n",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "nok, callNext=false",
|
|
|
|
givenCallNext: false,
|
|
|
|
givenErrorHandler: func(c echo.Context, err error) error {
|
|
|
|
return err
|
|
|
|
},
|
|
|
|
whenAuthHeaders: []string{}, // no JWT header
|
|
|
|
expectCode: http.StatusUnauthorized,
|
|
|
|
expect: "{\"message\":\"missing or malformed jwt\"}\n",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, tc := range testCases {
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
e := echo.New()
|
|
|
|
|
|
|
|
e.GET("/", func(c echo.Context) error {
|
|
|
|
token := c.Get("user").(string)
|
|
|
|
return c.String(http.StatusTeapot, token)
|
|
|
|
})
|
|
|
|
|
|
|
|
mw, err := JWTConfig{
|
|
|
|
TokenLookup: tc.givenTokenLookup,
|
|
|
|
ParseTokenFunc: func(c echo.Context, auth string) (interface{}, error) {
|
|
|
|
return tc.whenParseReturn, tc.whenParseError
|
|
|
|
},
|
|
|
|
ErrorHandler: tc.givenErrorHandler,
|
|
|
|
}.ToMiddleware()
|
|
|
|
assert.NoError(t, err)
|
|
|
|
e.Use(mw)
|
|
|
|
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
|
|
for _, a := range tc.whenAuthHeaders {
|
|
|
|
req.Header.Add(echo.HeaderAuthorization, a)
|
|
|
|
}
|
|
|
|
res := httptest.NewRecorder()
|
|
|
|
e.ServeHTTP(res, req)
|
|
|
|
|
|
|
|
assert.Equal(t, tc.expect, res.Body.String())
|
|
|
|
assert.Equal(t, tc.expectCode, res.Code)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|