2015-05-11 15:43:54 -07:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"testing"
|
2015-05-17 22:54:29 -07:00
|
|
|
|
2016-04-25 10:58:11 -07:00
|
|
|
"github.com/dgrijalva/jwt-go"
|
2015-05-17 22:54:29 -07:00
|
|
|
"github.com/labstack/echo"
|
2016-01-28 23:46:11 -08:00
|
|
|
"github.com/labstack/echo/test"
|
2015-05-30 10:54:55 -07:00
|
|
|
"github.com/stretchr/testify/assert"
|
2015-05-11 15:43:54 -07:00
|
|
|
)
|
|
|
|
|
2016-05-07 07:45:03 -07:00
|
|
|
func TestJWT(t *testing.T) {
|
2016-04-25 10:58:11 -07:00
|
|
|
e := echo.New()
|
|
|
|
req := test.NewRequest(echo.GET, "/", nil)
|
|
|
|
res := test.NewResponseRecorder()
|
|
|
|
c := e.NewContext(req, res)
|
|
|
|
handler := func(c echo.Context) error {
|
|
|
|
return c.String(http.StatusOK, "test")
|
|
|
|
}
|
2016-05-07 07:45:03 -07:00
|
|
|
config := JWTConfig{}
|
2016-04-25 10:58:11 -07:00
|
|
|
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
|
|
|
|
|
|
|
|
// No signing key provided
|
|
|
|
assert.Panics(t, func() {
|
2016-05-07 07:45:03 -07:00
|
|
|
JWTWithConfig(config)
|
2016-04-25 10:58:11 -07:00
|
|
|
})
|
|
|
|
|
|
|
|
// Unexpected signing method
|
2016-04-26 02:10:57 -07:00
|
|
|
config.SigningKey = []byte("secret")
|
2016-04-25 10:58:11 -07:00
|
|
|
config.SigningMethod = "RS256"
|
2016-05-07 07:45:03 -07:00
|
|
|
h := JWTWithConfig(config)(handler)
|
2016-04-25 10:58:11 -07:00
|
|
|
he := h(c).(*echo.HTTPError)
|
|
|
|
assert.Equal(t, http.StatusBadRequest, he.Code)
|
|
|
|
|
|
|
|
// Invalid key
|
|
|
|
auth := bearer + " " + token
|
|
|
|
req.Header().Set(echo.HeaderAuthorization, auth)
|
2016-04-26 02:10:57 -07:00
|
|
|
config.SigningKey = []byte("invalid-key")
|
2016-05-07 07:45:03 -07:00
|
|
|
h = JWTWithConfig(config)(handler)
|
2016-04-25 10:58:11 -07:00
|
|
|
he = h(c).(*echo.HTTPError)
|
2016-03-11 07:53:54 -08:00
|
|
|
assert.Equal(t, http.StatusUnauthorized, he.Code)
|
2016-04-25 10:58:11 -07:00
|
|
|
|
|
|
|
// Valid JWT
|
2016-05-07 07:45:03 -07:00
|
|
|
h = JWT([]byte("secret"))(handler)
|
2016-04-25 10:58:11 -07:00
|
|
|
if assert.NoError(t, h(c)) {
|
|
|
|
user := c.Get("user").(*jwt.Token)
|
|
|
|
assert.Equal(t, user.Claims["name"], "John Doe")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Invalid Authorization header
|
|
|
|
req.Header().Set(echo.HeaderAuthorization, "invalid-auth")
|
2016-05-07 07:45:03 -07:00
|
|
|
h = JWT([]byte("secret"))(handler)
|
2016-04-25 10:58:11 -07:00
|
|
|
he = h(c).(*echo.HTTPError)
|
|
|
|
assert.Equal(t, http.StatusBadRequest, he.Code)
|
2015-05-11 15:43:54 -07:00
|
|
|
}
|