Skip to content

Commit

Permalink
Handle obfuscated tokens
Browse files Browse the repository at this point in the history
Add field TokenDeobfuscatorFunc in Config which allow to give a function which is responsible of token deobfuscation.
Obfuscation prevent from token information disclosure attack.
  • Loading branch information
lvjp committed Oct 13, 2024
1 parent f4145f7 commit 140fca2
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
5 changes: 5 additions & 0 deletions jwt/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ type Config struct {
// - "cookie:<name>"
TokenLookup string

// TokenDeobfuscatorFunc defines a function to deobfuscate the founded token with [TokenLookup].
// This help to implement a Token obfuscation algoritm to prevent information disclosure.
// Optional. Default: nil
TokenDeobfuscatorFunc func(obfuscatedToken string) (string, error)

// AuthScheme to be used in the Authorization header.
// Optional. Default: "Bearer".
AuthScheme string
Expand Down
8 changes: 8 additions & 0 deletions jwt/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ func New(config ...Config) fiber.Handler {
if err != nil {
return cfg.ErrorHandler(c, err)
}

if cfg.TokenDeobfuscatorFunc != nil {
auth, err = cfg.TokenDeobfuscatorFunc(auth)
if err != nil {
return cfg.ErrorHandler(c, err)
}
}

var token *jwt.Token

if _, ok := cfg.Claims.(jwt.MapClaims); ok {
Expand Down
42 changes: 42 additions & 0 deletions jwt/jwt_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package jwtware_test

import (
"encoding/hex"
"fmt"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -104,6 +105,47 @@ const (
`
)

func TestJwtDeobfuscation(t *testing.T) {
t.Parallel()

defer func() {
// Assert
if err := recover(); err != nil {
t.Fatalf("Middleware should not panic")
}
}()

for _, test := range hamac {
// Arrange
app := fiber.New()

app.Use(jwtware.New(jwtware.Config{
SigningKey: jwtware.SigningKey{
JWTAlg: test.SigningMethod,
Key: []byte(defaultSigningKey),
},
TokenDeobfuscatorFunc: func(obfuscatedToken string) (string, error) {
token, err := hex.DecodeString(obfuscatedToken)
return string(token), err
},
}))

app.Get("/ok", func(c *fiber.Ctx) error {
return c.SendString("OK")
})

req := httptest.NewRequest("GET", "/ok", nil)
req.Header.Add("Authorization", "Bearer "+hex.EncodeToString([]byte(test.Token)))

// Act
resp, err := app.Test(req)

// Assert
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, 200, resp.StatusCode)
}
}

func TestJwtFromHeader(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 140fca2

Please sign in to comment.