Compare commits

...

5 Commits

Author SHA1 Message Date
Maxim Lebedev 44e3ff6eb5
⬆️ Upgraded JWX package 2022-06-10 00:05:52 +05:00
Maxim Lebedev eb02839e54
🐛 Fixed invalid slice indexing for JWT value 2022-02-26 04:16:11 +05:00
Maxim Lebedev 3672d2fcad
⬆️ Upgraded go modules 2022-02-26 04:09:56 +05:00
Maxim Lebedev 7375a6e8ed
Added param extractor 2022-02-26 03:18:49 +05:00
Maxim Lebedev a214a7e9e8
♻️ Refactored value extractors for middlewares 2022-02-26 03:18:22 +05:00
5 changed files with 421 additions and 305 deletions

234
csrf.go
View File

@ -5,105 +5,104 @@ import (
"crypto/subtle"
"encoding/base64"
"errors"
"strings"
"time"
http "github.com/valyala/fasthttp"
)
type (
// CSRFConfig defines the config for CSRF middleware.
CSRFConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// CSRFConfig defines the config for CSRF middleware.
type CSRFConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Max age (in seconds) of the CSRF cookie.
//
// Optional. Default value 86400 (24hr).
CookieMaxAge time.Duration
// Indicates SameSite mode of the CSRF cookie.
//
// Optional. Default value SameSiteDefaultMode.
CookieSameSite http.CookieSameSite
// Indicates SameSite mode of the CSRF cookie.
//
// Optional. Default value SameSiteDefaultMode.
CookieSameSite http.CookieSameSite
// Context key to store generated CSRF token into context.
//
// Optional. Default value "csrf".
ContextKey string
// Context key to store generated CSRF token into context.
//
// Optional. Default value "csrf".
ContextKey string
// Domain of the CSRF cookie.
//
// Optional. Default value none.
CookieDomain string
// Domain of the CSRF cookie.
//
// Optional. Default value none.
CookieDomain string
// Name of the CSRF cookie. This cookie will store CSRF token.
//
// Optional. Default value "csrf".
CookieName string
// Name of the CSRF cookie. This cookie will store CSRF token.
//
// Optional. Default value "csrf".
CookieName string
// Path of the CSRF cookie.
//
// Optional. Default value none.
CookiePath string
// Path of the CSRF cookie.
//
// Optional. Default value none.
CookiePath string
// TokenLookup is a string in the form of "<source>:<key>" that is used
// to extract token from the request.
// Possible values:
// - "header:<name>"
// - "form:<name>"
// - "query:<name>"
//
// Optional. Default value "header:X-CSRF-Token".
TokenLookup string
// TokenLookup is a string in the form of "<source>:<key>" that is used
// to extract token from the request.
// Possible values:
// - "header:<name>"
// - "form:<name>"
// - "query:<name>"
//
// Optional. Default value "header:X-CSRF-Token".
TokenLookup string
// Max age (in seconds) of the CSRF cookie.
//
// Optional. Default value 86400 (24hr).
CookieMaxAge int
// TokenLength is the length of the generated token.
//
// Optional. Default value 32.
TokenLength int
// TokenLength is the length of the generated token.
//
// Optional. Default value 32.
TokenLength int
// Indicates if CSRF cookie is secure.
//
// Optional. Default value false.
CookieSecure bool
// Indicates if CSRF cookie is secure.
//
// Optional. Default value false.
CookieSecure bool
// Indicates if CSRF cookie is HTTP only.
//
// Optional. Default value false.
CookieHTTPOnly bool
}
csrfTokenExtractor func(*http.RequestCtx) ([]byte, error)
)
// HeaderXCSRFToken describes the name of the header with the CSRF token.
const HeaderXCSRFToken string = "X-CSRF-Token"
// Possible CSRF errors.
var (
ErrMissingFormToken = errors.New("missing csrf token in the form parameter")
ErrMissingQueryToken = errors.New("missing csrf token in the query string")
)
// DefaultCSRFConfig contains the default CSRF middleware configuration.
//nolint: gochecknoglobals, gomnd
var DefaultCSRFConfig = CSRFConfig{
Skipper: DefaultSkipper,
CookieMaxAge: 24 * time.Hour,
CookieSameSite: http.CookieSameSiteDefaultMode,
ContextKey: "csrf",
CookieDomain: "",
CookieName: "_csrf",
CookiePath: "",
TokenLookup: "header:" + HeaderXCSRFToken,
TokenLength: 32,
CookieSecure: false,
CookieHTTPOnly: false,
// Indicates if CSRF cookie is HTTP only.
//
// Optional. Default value false.
CookieHTTPOnly bool
}
const (
ExtractorLimit int = 20
// HeaderXCSRFToken describes the name of the header with the CSRF token.
HeaderXCSRFToken string = "X-CSRF-Token"
)
var (
ErrCSRFInvalid = errors.New("invalid csrf token")
// DefaultCSRFConfig contains the default CSRF middleware configuration.
//nolint: gochecknoglobals, gomnd
DefaultCSRFConfig = CSRFConfig{
Skipper: DefaultSkipper,
CookieMaxAge: 86400,
CookieSameSite: http.CookieSameSiteDefaultMode,
ContextKey: "csrf",
CookieDomain: "",
CookieName: "_csrf",
CookiePath: "",
TokenLookup: "header:" + HeaderXCSRFToken,
TokenLength: 32,
CookieSecure: true,
CookieHTTPOnly: false,
}
)
// CSRF returns a Cross-Site Request Forgery (CSRF) middleware.
func CSRF() Interceptor {
return CSRFWithConfig(DefaultCSRFConfig)
config := DefaultCSRFConfig
return CSRFWithConfig(config)
}
// CSRFWithConfig returns a CSRF middleware with config.
@ -134,17 +133,12 @@ func CSRFWithConfig(config CSRFConfig) Interceptor {
}
if config.CookieSameSite == http.CookieSameSiteNoneMode {
config.CookieSecure = true
config.CookieSecure = DefaultCSRFConfig.CookieSecure
}
parts := strings.Split(config.TokenLookup, ":")
extractor := csrfTokenFromHeader(parts[1])
switch parts[0] {
case "form":
extractor = csrfTokenFromForm(parts[1])
case "query":
extractor = csrfTokenFromQuery(parts[1])
extractors, err := createExtractors(config.TokenLookup, "")
if err != nil {
panic("middleware: csrf: " + err.Error())
}
return func(ctx *http.RequestCtx, next http.RequestHandler) {
@ -171,16 +165,36 @@ func CSRFWithConfig(config CSRFConfig) Interceptor {
switch {
case ctx.IsGet(), ctx.IsHead(), ctx.IsOptions(), ctx.IsTrace():
default:
// NOTE(toby3d): validate token only for requests which are not defined as 'safe' by RFC7231
clientToken, err := extractor(ctx)
if err != nil {
ctx.Error(err.Error(), http.StatusBadRequest)
var lastExtractorErr, lastTokenErr error
return
outer:
for _, extractor := range extractors {
clientTokens, err := extractor(ctx)
if err != nil {
lastExtractorErr = err
continue
}
for _, clientToken := range clientTokens {
if !validateCSRFToken(token, clientToken) {
lastTokenErr = ErrCSRFInvalid
continue
}
lastTokenErr, lastExtractorErr = nil, nil
break outer
}
}
if !validateCSRFToken(token, clientToken) {
ctx.Error("invalid csrf token", http.StatusForbidden)
if lastTokenErr != nil {
ctx.Error(lastTokenErr.Error(), http.StatusInternalServerError)
return
} else if lastExtractorErr != nil {
ctx.Error(lastExtractorErr.Error(), http.StatusBadRequest)
return
}
@ -205,7 +219,7 @@ func CSRFWithConfig(config CSRFConfig) Interceptor {
cookie.SetSameSite(config.CookieSameSite)
}
cookie.SetExpire(time.Now().Add(config.CookieMaxAge))
cookie.SetExpire(time.Now().Add(time.Duration(config.CookieMaxAge) * time.Second))
cookie.SetSecure(config.CookieSecure)
cookie.SetHTTPOnly(config.CookieHTTPOnly)
ctx.Response.Header.SetCookie(cookie)
@ -220,32 +234,6 @@ func CSRFWithConfig(config CSRFConfig) Interceptor {
}
}
func csrfTokenFromHeader(header string) csrfTokenExtractor {
return func(ctx *http.RequestCtx) ([]byte, error) {
return ctx.Request.Header.Peek(header), nil
}
}
func csrfTokenFromForm(param string) csrfTokenExtractor {
return func(ctx *http.RequestCtx) ([]byte, error) {
if token := ctx.FormValue(param); token != nil {
return token, nil
}
return nil, ErrMissingFormToken
}
}
func csrfTokenFromQuery(param string) csrfTokenExtractor {
return func(ctx *http.RequestCtx) ([]byte, error) {
if !ctx.QueryArgs().Has(param) {
return nil, ErrMissingQueryToken
}
return ctx.QueryArgs().Peek(param), nil
}
}
func validateCSRFToken(token, clientToken []byte) bool {
return subtle.ConstantTimeCompare(token, clientToken) == 1
}

177
extractor.go Normal file
View File

@ -0,0 +1,177 @@
package middleware
import (
"bytes"
"errors"
"fmt"
"net/textproto"
"strings"
http "github.com/valyala/fasthttp"
)
// ValuesExtractor defines a function for extracting values (keys/tokens) from
// the given context.
type ValuesExtractor func(ctx *http.RequestCtx) ([][]byte, error)
const (
// extractorLimit is arbitrary number to limit values extractor can
// return. this limits possible resource exhaustion attack vector.
extractorLimit = 20
)
var (
errHeaderExtractorValueMissing = errors.New("missing value in request header")
errHeaderExtractorValueInvalid = errors.New("invalid value in request header")
errQueryExtractorValueMissing = errors.New("missing value in the query string")
errParamExtractorValueMissing = errors.New("missing value in path params")
errCookieExtractorValueMissing = errors.New("missing value in cookies")
errFormExtractorValueMissing = errors.New("missing value in the form")
)
func createExtractors(lookups, authScheme string) ([]ValuesExtractor, error) {
if lookups == "" {
return nil, nil
}
sources := strings.Split(lookups, ",")
extractors := make([]ValuesExtractor, 0)
for _, source := range sources {
parts := strings.Split(source, ":")
if len(parts) < 2 {
return nil, fmt.Errorf("extractor source for lookup could not be split into needed parts: %s",
source)
}
switch parts[0] {
case "query":
extractors = append(extractors, valuesFromQuery(parts[1]))
case "param":
extractors = append(extractors, valuesFromParam(parts[1]))
case "cookie":
extractors = append(extractors, valuesFromCookie(parts[1]))
case "form":
extractors = append(extractors, valuesFromForm(parts[1]))
case "header":
prefix := ""
if len(parts) > 2 {
prefix = parts[2]
} else if authScheme != "" && parts[1] == http.HeaderAuthorization {
// backwards compatibility for JWT and KeyAuth:
// * we only apply this fix to Authorization as header we use and uses prefixes like "Bearer <token-value>" etc
// * previously header extractor assumed that auth-scheme/prefix had a space as suffix we need to retain that
// behaviour for default values and Authorization header.
prefix = authScheme
if !strings.HasSuffix(prefix, " ") {
prefix += " "
}
}
extractors = append(extractors, valuesFromHeader(parts[1], prefix))
}
}
return extractors, nil
}
// valuesFromHeader returns a functions that extracts values from the request header.
// valuePrefix is parameter to remove first part (prefix) of the extracted value. This is useful if header value has static
// prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we want to remove is `<auth-scheme> `
// note the space at the end. In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove
// is `Basic `. In case of JWT tokens `Authorization: Bearer <token>` prefix is `Bearer `.
// If prefix is left empty the whole value is returned.
func valuesFromHeader(header, valuePrefix string) ValuesExtractor {
prefixLen := len(valuePrefix)
// standard library parses http.Request header keys in canonical form but we may provide something else so fix this
header = textproto.CanonicalMIMEHeaderKey(header)
return func(ctx *http.RequestCtx) ([][]byte, error) {
value := ctx.Request.Header.Peek(header)
if len(value) == 0 {
return nil, errHeaderExtractorValueMissing
}
if prefixLen == 0 {
return append([][]byte{}, value), nil
}
if len(value) > prefixLen && bytes.EqualFold(value[:prefixLen], []byte(valuePrefix)) {
return append([][]byte{}, value[prefixLen:]), nil
}
return nil, errHeaderExtractorValueInvalid
}
}
// valuesFromQuery returns a function that extracts values from the query string.
func valuesFromQuery(param string) ValuesExtractor {
return func(ctx *http.RequestCtx) ([][]byte, error) {
if !ctx.QueryArgs().Has(param) {
return nil, errQueryExtractorValueMissing
}
result := ctx.QueryArgs().PeekMulti(param)
if len(result) > extractorLimit-1 {
result = result[:extractorLimit]
}
return result, nil
}
}
// valuesFromParam returns a function that extracts values from the url param string.
func valuesFromParam(param string) ValuesExtractor {
return func(ctx *http.RequestCtx) ([][]byte, error) {
if !ctx.PostArgs().Has(param) {
return nil, errParamExtractorValueMissing
}
result := ctx.PostArgs().PeekMulti(param)
if len(result) > extractorLimit-1 {
result = result[:extractorLimit]
}
return result, nil
}
}
// valuesFromCookie returns a function that extracts values from the named cookie.
func valuesFromCookie(name string) ValuesExtractor {
return func(ctx *http.RequestCtx) ([][]byte, error) {
if value := ctx.Request.Header.Cookie(name); len(value) != 0 {
return append([][]byte{}, value), nil
}
return nil, errCookieExtractorValueMissing
}
}
// valuesFromForm returns a function that extracts values from the form field.
func valuesFromForm(name string) ValuesExtractor {
return func(ctx *http.RequestCtx) ([][]byte, error) {
form, err := ctx.MultipartForm()
if err != nil {
return nil, fmt.Errorf("valuesFromForm parse form failed: %w", err)
}
values := form.Value[name]
switch {
case len(values) == 0:
return nil, errFormExtractorValueMissing
case len(values) > extractorLimit-1:
values = values[:extractorLimit]
}
result := make([][]byte, 0)
for i := range values {
result = append(result, []byte(values[i]))
}
return result, nil
}
}

25
go.mod
View File

@ -3,27 +3,26 @@ module source.toby3d.me/toby3d/middleware
go 1.17
require (
github.com/fasthttp/session/v2 v2.4.4
github.com/fasthttp/session/v2 v2.4.11
github.com/go-logfmt/logfmt v0.5.1
github.com/lestrrat-go/jwx v1.2.14
github.com/valyala/fasthttp v1.31.0
github.com/lestrrat-go/jwx/v2 v2.0.2
github.com/valyala/fasthttp v1.37.0
)
require (
github.com/andybalholm/brotli v1.0.4 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/goccy/go-json v0.9.0 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect
github.com/lestrrat-go/blackmagic v1.0.0 // indirect
github.com/lestrrat-go/httpcc v1.0.0 // indirect
github.com/lestrrat-go/iter v1.0.1 // indirect
github.com/goccy/go-json v0.9.7 // indirect
github.com/klauspost/compress v1.15.6 // indirect
github.com/lestrrat-go/blackmagic v1.0.1 // indirect
github.com/lestrrat-go/httpcc v1.0.1 // indirect
github.com/lestrrat-go/httprc v1.0.1 // indirect
github.com/lestrrat-go/iter v1.0.2 // indirect
github.com/lestrrat-go/option v1.0.0 // indirect
github.com/philhofer/fwd v1.1.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/savsgio/dictpool v0.0.0-20210921080634-84324d0689d7 // indirect
github.com/savsgio/gotils v0.0.0-20211223103454-d0aaa54c5899 // indirect
github.com/savsgio/dictpool v0.0.0-20220406081701-03de5edb2e6d // indirect
github.com/savsgio/gotils v0.0.0-20220530130905-52f3993e8d6d // indirect
github.com/tinylib/msgp v1.1.6 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect
)

96
go.sum
View File

@ -1,28 +1,28 @@
github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d/go.mod h1:tmAIfUFEirG/Y8jhZ9M+h36obRZAk/1fcSpXwAVlfqE=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fasthttp/session/v2 v2.4.4 h1:xJOyPT8oIAeDXwCDnDyz52x44BxVRTCRNhYeMNj8xUE=
github.com/fasthttp/session/v2 v2.4.4/go.mod h1:qemCSBS6ozHzh5RVPMQzAFklcAhLqLtsoGTz1OPT5kM=
github.com/fasthttp/session/v2 v2.4.11 h1:ZPiKk0pkBl7umMVq1nOdvRgjn9Kfc5RzusPjnYckP84=
github.com/fasthttp/session/v2 v2.4.11/go.mod h1:mHFWv73p5vYJaTZQDPokykT4GVOxfOoHGag/DlX8FzU=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA=
github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/go-redis/redis/v8 v8.11.4/go.mod h1:2Z2wHZXdQpCDXEGzqMockDpNyYvi2l4Pxt6RJr792+w=
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/goccy/go-json v0.8.1/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-json v0.9.0 h1:2flW7bkbrRgU8VuDi0WXDqTmPimjv1thfxkPe8sug+8=
github.com/goccy/go-json v0.9.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-json v0.9.7 h1:IcB+Aqpx/iMHu5Yooh7jEzJk1JZ7Pjtmys2ukPr7EeM=
github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
@ -32,80 +32,80 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg=
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A=
github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y=
github.com/lestrrat-go/blackmagic v1.0.0 h1:XzdxDbuQTz0RZZEmdU7cnQxUtFUzgCSPq8RCz4BxIi4=
github.com/lestrrat-go/blackmagic v1.0.0/go.mod h1:TNgH//0vYSs8VXDCfkZLgIrVTTXQELZffUV0tz3MtdQ=
github.com/lestrrat-go/httpcc v1.0.0 h1:FszVC6cKfDvBKcJv646+lkh4GydQg2Z29scgUfkOpYc=
github.com/lestrrat-go/httpcc v1.0.0/go.mod h1:tGS/u00Vh5N6FHNkExqGGNId8e0Big+++0Gf8MBnAvE=
github.com/lestrrat-go/iter v1.0.1 h1:q8faalr2dY6o8bV45uwrxq12bRa1ezKrB6oM9FUgN4A=
github.com/lestrrat-go/iter v1.0.1/go.mod h1:zIdgO1mRKhn8l9vrZJZz9TUMMFbQbLeTsbqPDrJ/OJc=
github.com/lestrrat-go/jwx v1.2.14 h1:69OeaiFKCTn8xDmBGzHTgv/GBoO1LJcXw99GfYCDKzg=
github.com/lestrrat-go/jwx v1.2.14/go.mod h1:3Q3Re8TaOcVTdpx4Tvz++OWmryDklihTDqrrwQiyS2A=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/compress v1.15.6 h1:6D9PcO8QWu0JyaQ2zUMmu16T1T+zjjEpP91guRsvDfY=
github.com/klauspost/compress v1.15.6/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/lestrrat-go/blackmagic v1.0.1 h1:lS5Zts+5HIC/8og6cGHb0uCcNCa3OUt1ygh3Qz2Fe80=
github.com/lestrrat-go/blackmagic v1.0.1/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU=
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
github.com/lestrrat-go/httprc v1.0.1 h1:Cnc4NxIySph38pQPzKbjg5OkKsGR/Cf5xcWt5OlSUDI=
github.com/lestrrat-go/httprc v1.0.1/go.mod h1:5Ml+nB++j6IC0e6LzefJnrpMQDKgDwDCaIQQzhbqhJM=
github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI=
github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4=
github.com/lestrrat-go/jwx/v2 v2.0.2 h1:wkq9jwCkF3xrykISzn0Eksd7NEMOZ9yvCdnEpovIJX8=
github.com/lestrrat-go/jwx/v2 v2.0.2/go.mod h1:xV8+xRcrKbmnScV8adOzUuuTrL8aAZJoY4q2JAqIYU8=
github.com/lestrrat-go/option v1.0.0 h1:WqAWL8kh8VcSoD6xjSH34/1m8yxluXQbDeKNfvFeEO4=
github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
github.com/lib/pq v1.10.3/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.8/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.13/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/ginkgo/v2 v2.0.0/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
github.com/philhofer/fwd v1.1.1 h1:GdGcTjf5RNAxwS4QLsiMzJYj5KEvPJD3Abr261yRQXQ=
github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/savsgio/dictpool v0.0.0-20210921080634-84324d0689d7 h1:xpWch10f2FeD/0DhPmyBOAq7bhnz4bWoQA6MpX+WHuA=
github.com/savsgio/dictpool v0.0.0-20210921080634-84324d0689d7/go.mod h1:Yk5UwqSnptrDwMGAvYa96KVGp34nYCBuLbZNLf/L61o=
github.com/savsgio/gotils v0.0.0-20210921075833-21a6215cb0e4/go.mod h1:oejLrk1Y/5zOF+c/aHtXqn3TFlzzbAgPWg8zBiAHDas=
github.com/savsgio/gotils v0.0.0-20211223103454-d0aaa54c5899 h1:Orn7s+r1raRTBKLSc9DmbktTT04sL+vkzsbRD2Q8rOI=
github.com/savsgio/gotils v0.0.0-20211223103454-d0aaa54c5899/go.mod h1:oejLrk1Y/5zOF+c/aHtXqn3TFlzzbAgPWg8zBiAHDas=
github.com/savsgio/dictpool v0.0.0-20220406081701-03de5edb2e6d h1:ICMDEgNgR5xFW6ZDeMKTtmh07YiLr7GkDw897I2DwKg=
github.com/savsgio/dictpool v0.0.0-20220406081701-03de5edb2e6d/go.mod h1:jrsy/bTK2n5uybo7bAvtLGzmuzAbxp+nKS8bzgrZURE=
github.com/savsgio/gotils v0.0.0-20220401102855-e56b59f40436/go.mod h1:Gy+0tqhJvgGlqnTF8CVGP0AaGRjwBtXs/a5PA0Y3+A4=
github.com/savsgio/gotils v0.0.0-20220530130905-52f3993e8d6d h1:Q+gqLBOPkFGHyCJxXMRqtUgUbTjI8/Ze8vu8GGyNFwo=
github.com/savsgio/gotils v0.0.0-20220530130905-52f3993e8d6d/go.mod h1:Gy+0tqhJvgGlqnTF8CVGP0AaGRjwBtXs/a5PA0Y3+A4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tinylib/msgp v1.1.6 h1:i+SbKraHhnrf9M5MYmvQhFnbLhAXSDWF8WWsuyRdocw=
github.com/tinylib/msgp v1.1.6/go.mod h1:75BAfg2hauQhs3qedfdDZmWAPcFMAvJE5b9rGOMufyw=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.31.0 h1:lrauRLII19afgCs2fnWRJ4M5IkV0lo2FqA61uGkNBfE=
github.com/valyala/fasthttp v1.31.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus=
github.com/valyala/fasthttp v1.37.0 h1:7WHCyI7EAkQMVmrfBhWTCOaeROb1aCBiTopx63LkMbE=
github.com/valyala/fasthttp v1.37.0/go.mod h1:t/G+3rLek+CyY9bnIE+YlMRddxVAAGjhxndDB4i4C0I=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201217014255-9d1352758620/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 h1:0es+/5331RGQPcXlMfP+WrnIIS6dNnNRe0WB02W0F4M=
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e h1:T8NU3HyQ8ClP4SEE+KbFlg6n0NhuTsN4MyznaarGsZM=
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -114,20 +114,22 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=

194
jwt.go
View File

@ -1,13 +1,11 @@
package middleware
import (
"bytes"
"errors"
"fmt"
"strings"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwt"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwt"
http "github.com/valyala/fasthttp"
)
@ -83,6 +81,14 @@ type (
// - "header: Authorization,cookie: myowncookie"
TokenLookup string
// TokenLookupFuncs defines a list of user-defined functions
// that extract JWT token from the given context.
// This is one of the two options to provide a token extractor.
// The order of precedence is user-defined TokenLookupFuncs, and
// TokenLookup.
// You can also provide both if you want.
TokenLookupFuncs []ValuesExtractor
// AuthScheme to be used in the Authorization header.
//
// Optional. Default value "Bearer".
@ -110,6 +116,17 @@ type (
// fails or parsed token is invalid. Defaults to implementation
// using `github.com/golang-jwt/jwt` as JWT implementation library
ParseTokenFunc func(auth []byte, ctx *http.RequestCtx) (interface{}, error)
// ContinueOnIgnoredError allows the next middleware/handler to
// be called when ErrorHandlerWithContext decides to ignore the
// error (by returning `nil`). This is useful when parts of your
// site/api allow public access and some authorized routes
// provide extra functionality. In that case you can use
// ErrorHandlerWithContext to set a default public JWT token
// value in the request context and continue. Some logic down
// the remaining execution chain needs to check that (public)
// token value then.
ContinueOnIgnoredError bool
}
// JWTSuccessHandler defines a function which is executed for a valid
@ -122,27 +139,18 @@ type (
// JWTErrorHandlerWithContext is almost identical to JWTErrorHandler,
// but it's passed the current context.
JWTErrorHandlerWithContext func(err error, ctx *http.RequestCtx)
JWTErrorHandlerWithContext func(err error, ctx *http.RequestCtx) error
jwtExtractor func(ctx *http.RequestCtx) ([]byte, error)
)
// Variants of token sources.
const (
SourceCookie = "cookie"
SourceForm = "form"
SourceHeader = "header"
SourceParam = "param"
SourceQuery = "query"
)
// DefaultJWTConfig is the default JWT auth middleware config.
//nolint: gochecknoglobals
var DefaultJWTConfig = JWTConfig{
Skipper: DefaultSkipper,
SigningMethod: "HS256",
ContextKey: "user",
TokenLookup: SourceHeader + ":" + http.HeaderAuthorization,
TokenLookup: "header:" + http.HeaderAuthorization,
AuthScheme: "Bearer",
Claims: []jwt.ClaimPair{},
}
@ -159,7 +167,10 @@ var (
// * For invalid token, it returns "401 - Unauthorized" error.
// * For missing token, it returns "400 - Bad Request" error.
func JWT(key interface{}) Interceptor {
return JWTWithConfig(DefaultJWTConfig)
config := DefaultJWTConfig
config.SigningKey = key
return JWTWithConfig(config)
}
// JWTWithConfig returns a JWT auth middleware with config.
@ -198,24 +209,13 @@ func JWTWithConfig(config JWTConfig) Interceptor {
config.ParseTokenFunc = config.defaultParseToken
}
extractors := make([]jwtExtractor, 0)
sources := strings.Split(config.TokenLookup, ",")
extractors, err := createExtractors(config.TokenLookup, config.AuthScheme)
if err != nil {
panic("middleware: jwt: " + err.Error())
}
for _, source := range sources {
parts := strings.Split(source, ":")
switch parts[0] {
case SourceQuery:
extractors = append(extractors, jwtFromQuery(parts[1]))
case SourceParam:
extractors = append(extractors, jwtFromParam(parts[1]))
case SourceCookie:
extractors = append(extractors, jwtFromCookie(parts[1]))
case SourceForm:
extractors = append(extractors, jwtFromForm(parts[1]))
case SourceHeader:
extractors = append(extractors, jwtFromHeader(parts[1], config.AuthScheme))
}
if len(config.TokenLookupFuncs) > 0 {
extractors = append(config.TokenLookupFuncs, extractors...)
}
return func(ctx *http.RequestCtx, next http.RequestHandler) {
@ -229,45 +229,39 @@ func JWTWithConfig(config JWTConfig) Interceptor {
config.BeforeFunc(ctx)
}
var (
auth []byte
err error
)
var lastExtractorErr, lastTokenErr error
for _, extractor := range extractors {
if auth, err = extractor(ctx); err == nil {
break
}
}
auths, err := extractor(ctx)
if err != nil {
lastExtractorErr = ErrJWTMissing
if err != nil {
if config.ErrorHandler != nil {
config.ErrorHandler(err)
continue
}
for _, auth := range auths {
token, err := config.ParseTokenFunc(auth, ctx)
if err != nil {
lastTokenErr = err
continue
}
ctx.SetUserValue(config.ContextKey, token)
if config.SuccessHandler != nil {
config.SuccessHandler(ctx)
}
next(ctx)
return
}
if config.ErrorHandlerWithContext != nil {
config.ErrorHandlerWithContext(err, ctx)
return
}
ctx.Error(err.Error(), http.StatusInternalServerError)
return
}
if token, err := config.ParseTokenFunc(auth, ctx); err == nil {
ctx.SetUserValue(config.ContextKey, token)
if config.SuccessHandler != nil {
config.SuccessHandler(ctx)
}
next(ctx)
return
err := lastTokenErr
if err == nil {
err = lastExtractorErr
}
if config.ErrorHandler != nil {
@ -277,75 +271,31 @@ func JWTWithConfig(config JWTConfig) Interceptor {
}
if config.ErrorHandlerWithContext != nil {
config.ErrorHandlerWithContext(err, ctx)
tmpErr := config.ErrorHandlerWithContext(err, ctx)
if config.ContinueOnIgnoredError && tmpErr == nil {
next(ctx)
} else {
ctx.Error(tmpErr.Error(), http.StatusUnauthorized)
}
return
}
ctx.Error(ErrJWTInvalid.Error(), http.StatusUnauthorized)
if lastTokenErr != nil {
ctx.Error(lastTokenErr.Error(), http.StatusUnauthorized)
return
}
ctx.Error(err.Error(), http.StatusInternalServerError)
}
}
func (config *JWTConfig) defaultParseToken(auth []byte, ctx *http.RequestCtx) (interface{}, error) {
token, err := jwt.Parse(
auth, jwt.WithVerify(config.SigningMethod, config.SigningKey), jwt.WithValidate(true),
)
token, err := jwt.Parse(auth, jwt.WithKey(config.SigningMethod, config.SigningKey), jwt.WithVerify(true))
if err != nil {
return nil, fmt.Errorf("cannot parse JWT token: %w", err)
}
return token, nil
}
func jwtFromHeader(header, authScheme string) jwtExtractor {
return func(ctx *http.RequestCtx) ([]byte, error) {
auth := ctx.Request.Header.Peek(header)
l := len(authScheme)
if len(auth) > l+1 && bytes.EqualFold(auth[:l], []byte(authScheme)) {
return auth[l+1:], nil
}
return nil, ErrJWTMissing
}
}
func jwtFromQuery(param string) jwtExtractor {
return func(ctx *http.RequestCtx) ([]byte, error) {
if ctx.QueryArgs().Has(param) {
return nil, ErrJWTMissing
}
return ctx.QueryArgs().Peek(param), nil
}
}
func jwtFromParam(param string) jwtExtractor {
return func(ctx *http.RequestCtx) ([]byte, error) {
if !ctx.PostArgs().Has(param) {
return nil, ErrJWTMissing
}
return ctx.PostArgs().Peek(param), nil
}
}
func jwtFromCookie(name string) jwtExtractor {
return func(ctx *http.RequestCtx) ([]byte, error) {
if cookie := ctx.Request.Header.Cookie(name); cookie != nil {
return cookie, nil
}
return nil, ErrJWTMissing
}
}
func jwtFromForm(name string) jwtExtractor {
return func(ctx *http.RequestCtx) ([]byte, error) {
if field := ctx.FormValue(name); field != nil {
return field, nil
}
return nil, ErrJWTMissing
}
}