1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00
echo/middleware/jwt.go
Vishal Rana dc244c173d Minor fix in jwt and csrf middleware
Signed-off-by: Vishal Rana <vr@labstack.com>
2016-05-26 19:23:46 -07:00

144 lines
3.7 KiB
Go

package middleware
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
)
type (
// JWTConfig defines the config for JWT auth middleware.
JWTConfig struct {
// Signing key to validate token.
// Required.
SigningKey []byte `json:"signing_key"`
// Signing method, used to check token signing method.
// Optional. Default value HS256.
SigningMethod string `json:"signing_method"`
// Context key to store user information from the token into context.
// Optional. Default value "user".
ContextKey string `json:"context_key"`
// TokenLookup is a string in the form of "<source>:<name>" that is used
// to extract token from the request.
// Optional. Default value "header:Authorization".
// Possible values:
// - "header:<name>"
// - "query:<name>"
TokenLookup string `json:"token_lookup"`
}
jwtExtractor func(echo.Context) (string, error)
)
const (
bearer = "Bearer"
)
// Algorithims
const (
AlgorithmHS256 = "HS256"
)
var (
// DefaultJWTConfig is the default JWT auth middleware config.
DefaultJWTConfig = JWTConfig{
SigningMethod: AlgorithmHS256,
ContextKey: "user",
TokenLookup: "header:" + echo.HeaderAuthorization,
}
)
// JWT returns a JSON Web Token (JWT) auth middleware.
//
// For valid token, it sets the user in context and calls next handler.
// For invalid token, it sends "401 - Unauthorized" response.
// For empty or invalid `Authorization` header, it sends "400 - Bad Request".
//
// See: https://jwt.io/introduction
func JWT(key []byte) echo.MiddlewareFunc {
c := DefaultJWTConfig
c.SigningKey = key
return JWTWithConfig(c)
}
// JWTWithConfig returns a JWT auth middleware from config.
// See: `JWT()`.
func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
// Defaults
if config.SigningKey == nil {
panic("jwt middleware requires signing key")
}
if config.SigningMethod == "" {
config.SigningMethod = DefaultJWTConfig.SigningMethod
}
if config.ContextKey == "" {
config.ContextKey = DefaultJWTConfig.ContextKey
}
if config.TokenLookup == "" {
config.TokenLookup = DefaultJWTConfig.TokenLookup
}
// Initialize
parts := strings.Split(config.TokenLookup, ":")
extractor := jwtFromHeader(parts[1])
switch parts[0] {
case "query":
extractor = jwtFromQuery(parts[1])
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
auth, err := extractor(c)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
token, err := jwt.Parse(auth, func(t *jwt.Token) (interface{}, error) {
// Check the signing method
if t.Method.Alg() != config.SigningMethod {
return nil, fmt.Errorf("unexpected jwt signing method=%v", t.Header["alg"])
}
return config.SigningKey, nil
})
if err == nil && token.Valid {
// Store user information from token into context.
c.Set(config.ContextKey, token)
return next(c)
}
return echo.ErrUnauthorized
}
}
}
// jwtFromHeader returns a `jwtExtractor` that extracts token from the provided
// request header.
func jwtFromHeader(header string) jwtExtractor {
return func(c echo.Context) (string, error) {
auth := c.Request().Header().Get(header)
l := len(bearer)
if len(auth) > l+1 && auth[:l] == bearer {
return auth[l+1:], nil
}
return "", errors.New("empty or invalid jwt in authorization header")
}
}
// jwtFromQuery returns a `jwtExtractor` that extracts token from the provided query
// parameter.
func jwtFromQuery(param string) jwtExtractor {
return func(c echo.Context) (string, error) {
token := c.QueryParam(param)
if token == "" {
return "", errors.New("empty jwt in query param")
}
return token, nil
}
}