1
0
mirror of https://github.com/labstack/echo.git synced 2025-07-13 01:30:31 +02:00

JWTAuth to JWT

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2016-05-07 07:45:03 -07:00
parent 37f05202e8
commit e943ed24be
3 changed files with 22 additions and 22 deletions

View File

@ -239,7 +239,7 @@ Middleware | Description
[Recover](https://labstack.com/echo/guide/recover-middleware) | Recover from panics [Recover](https://labstack.com/echo/guide/recover-middleware) | Recover from panics
[Gzip](https://labstack.com/echo/guide/gzip-middleware) | Send gzip HTTP response [Gzip](https://labstack.com/echo/guide/gzip-middleware) | Send gzip HTTP response
[BasicAuth](https://labstack.com/echo/guide/basic-auth-middleware) | HTTP basic authentication [BasicAuth](https://labstack.com/echo/guide/basic-auth-middleware) | HTTP basic authentication
[JWTAuth](https://labstack.com/echo/guide/jwt-auth-middleware) | JWT authentication [JWTAuth](https://labstack.com/echo/guide/jwt-middleware) | JWT authentication
[Secure](https://labstack.com/echo/guide/secure-middleware) | Protection against attacks [Secure](https://labstack.com/echo/guide/secure-middleware) | Protection against attacks
[CORS](https://labstack.com/echo/guide/cors-middleware) | Cross-Origin Resource Sharing [CORS](https://labstack.com/echo/guide/cors-middleware) | Cross-Origin Resource Sharing
[Static](https://labstack.com/echo/guide/static-middleware) | Serve static files [Static](https://labstack.com/echo/guide/static-middleware) | Serve static files

View File

@ -9,8 +9,8 @@ import (
) )
type ( type (
// JWTAuthConfig defines the config for JWT auth middleware. // JWTConfig defines the config for JWT auth middleware.
JWTAuthConfig struct { JWTConfig struct {
// SigningKey is the key to validate token. // SigningKey is the key to validate token.
// Required. // Required.
SigningKey []byte SigningKey []byte
@ -44,42 +44,42 @@ const (
) )
var ( var (
// DefaultJWTAuthConfig is the default JWT auth middleware config. // DefaultJWTConfig is the default JWT auth middleware config.
DefaultJWTAuthConfig = JWTAuthConfig{ DefaultJWTConfig = JWTConfig{
SigningMethod: AlgorithmHS256, SigningMethod: AlgorithmHS256,
ContextKey: "user", ContextKey: "user",
Extractor: JWTFromHeader, Extractor: JWTFromHeader,
} }
) )
// JWTAuth returns a JSON Web Token (JWT) auth middleware. // JWT returns a JSON Web Token (JWT) auth middleware.
// //
// For valid token, it sets the user in context and calls next handler. // For valid token, it sets the user in context and calls next handler.
// For invalid token, it sends "401 - Unauthorized" response. // For invalid token, it sends "401 - Unauthorized" response.
// For empty or invalid `Authorization` header, it sends "400 - Bad Request". // For empty or invalid `Authorization` header, it sends "400 - Bad Request".
// //
// See https://jwt.io/introduction // See https://jwt.io/introduction
func JWTAuth(key []byte) echo.MiddlewareFunc { func JWT(key []byte) echo.MiddlewareFunc {
c := DefaultJWTAuthConfig c := DefaultJWTConfig
c.SigningKey = key c.SigningKey = key
return JWTAuthWithConfig(c) return JWTWithConfig(c)
} }
// JWTAuthWithConfig returns a JWT auth middleware from config. // JWTWithConfig returns a JWT auth middleware from config.
// See `JWTAuth()`. // See `JWT()`.
func JWTAuthWithConfig(config JWTAuthConfig) echo.MiddlewareFunc { func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
// Defaults // Defaults
if config.SigningKey == nil { if config.SigningKey == nil {
panic("jwt middleware requires signing key") panic("jwt middleware requires signing key")
} }
if config.SigningMethod == "" { if config.SigningMethod == "" {
config.SigningMethod = DefaultJWTAuthConfig.SigningMethod config.SigningMethod = DefaultJWTConfig.SigningMethod
} }
if config.ContextKey == "" { if config.ContextKey == "" {
config.ContextKey = DefaultJWTAuthConfig.ContextKey config.ContextKey = DefaultJWTConfig.ContextKey
} }
if config.Extractor == nil { if config.Extractor == nil {
config.Extractor = DefaultJWTAuthConfig.Extractor config.Extractor = DefaultJWTConfig.Extractor
} }
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {

View File

@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestJWTAuth(t *testing.T) { func TestJWT(t *testing.T) {
e := echo.New() e := echo.New()
req := test.NewRequest(echo.GET, "/", nil) req := test.NewRequest(echo.GET, "/", nil)
res := test.NewResponseRecorder() res := test.NewResponseRecorder()
@ -18,18 +18,18 @@ func TestJWTAuth(t *testing.T) {
handler := func(c echo.Context) error { handler := func(c echo.Context) error {
return c.String(http.StatusOK, "test") return c.String(http.StatusOK, "test")
} }
config := JWTAuthConfig{} config := JWTConfig{}
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
// No signing key provided // No signing key provided
assert.Panics(t, func() { assert.Panics(t, func() {
JWTAuthWithConfig(config) JWTWithConfig(config)
}) })
// Unexpected signing method // Unexpected signing method
config.SigningKey = []byte("secret") config.SigningKey = []byte("secret")
config.SigningMethod = "RS256" config.SigningMethod = "RS256"
h := JWTAuthWithConfig(config)(handler) h := JWTWithConfig(config)(handler)
he := h(c).(*echo.HTTPError) he := h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusBadRequest, he.Code) assert.Equal(t, http.StatusBadRequest, he.Code)
@ -37,12 +37,12 @@ func TestJWTAuth(t *testing.T) {
auth := bearer + " " + token auth := bearer + " " + token
req.Header().Set(echo.HeaderAuthorization, auth) req.Header().Set(echo.HeaderAuthorization, auth)
config.SigningKey = []byte("invalid-key") config.SigningKey = []byte("invalid-key")
h = JWTAuthWithConfig(config)(handler) h = JWTWithConfig(config)(handler)
he = h(c).(*echo.HTTPError) he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusUnauthorized, he.Code) assert.Equal(t, http.StatusUnauthorized, he.Code)
// Valid JWT // Valid JWT
h = JWTAuth([]byte("secret"))(handler) h = JWT([]byte("secret"))(handler)
if assert.NoError(t, h(c)) { if assert.NoError(t, h(c)) {
user := c.Get("user").(*jwt.Token) user := c.Get("user").(*jwt.Token)
assert.Equal(t, user.Claims["name"], "John Doe") assert.Equal(t, user.Claims["name"], "John Doe")
@ -50,7 +50,7 @@ func TestJWTAuth(t *testing.T) {
// Invalid Authorization header // Invalid Authorization header
req.Header().Set(echo.HeaderAuthorization, "invalid-auth") req.Header().Set(echo.HeaderAuthorization, "invalid-auth")
h = JWTAuth([]byte("secret"))(handler) h = JWT([]byte("secret"))(handler)
he = h(c).(*echo.HTTPError) he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusBadRequest, he.Code) assert.Equal(t, http.StatusBadRequest, he.Code)
} }