Skip to content

Commit 945e83f

Browse files
authored
Merge pull request #48 from agilezebra/47-headermap-array
Handle JSON types of array, object, null and boolean in claim->header
2 parents acf463a + 72fcbff commit 945e83f

File tree

2 files changed

+29
-9
lines changed

2 files changed

+29
-9
lines changed

jwt.go

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"context"
66
"crypto/tls"
77
"crypto/x509"
8+
"encoding/json"
89
"fmt"
910
"html"
1011
"html/template"
@@ -331,16 +332,30 @@ func (plugin *JWTPlugin) validate(request *http.Request, variables *TemplateVari
331332
}
332333
}
333334

334-
// Map any require claims to headers
335-
for header, claim := range plugin.headerMap {
336-
value, ok := claims[claim]
337-
if ok {
335+
plugin.mapClaimsToHeaders(claims, request)
336+
}
337+
338+
return http.StatusOK, nil
339+
}
340+
341+
// mapClaimsToHeaders maps any claims to headers as specified in the headerMap configuration.
342+
func (plugin *JWTPlugin) mapClaimsToHeaders(claims jwt.MapClaims, request *http.Request) {
343+
for header, claim := range plugin.headerMap {
344+
value, ok := claims[claim]
345+
if ok {
346+
switch value := value.(type) {
347+
case []any, map[string]any, nil:
348+
json, err := json.Marshal(value)
349+
if err == nil {
350+
request.Header.Add(header, string(json))
351+
}
352+
// Although we check err, we don't have a branch to log an error for err != nil, because it's not possible
353+
// that the value won't be marshallable to json, given it has already been unmarshalled _from_ json to get here
354+
default:
338355
request.Header.Add(header, fmt.Sprint(value))
339356
}
340357
}
341358
}
342-
343-
return http.StatusOK, nil
344359
}
345360

346361
// Validate checks value against the requirement, calling ourself recursively for object and array values.

jwt_test.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1141,15 +1141,20 @@ func TestServeHTTP(tester *testing.T) {
11411141
{
11421142
Name: "map headers",
11431143
Expect: http.StatusOK,
1144-
ExpectHeaders: map[string]string{"X-Id": "1234"},
1144+
ExpectHeaders: map[string]string{"X-Number": "1234", "X-Array": `["test",1,null]`, "X-Map": `{"a":1,"b":2}`, "X-Boolean": "true", "X-Null": "null", "X-Text": "Hello, world!"},
11451145
Config: `
11461146
secret: fixed secret
11471147
require:
11481148
aud: test
11491149
headerMap:
1150-
X-Id: user
1150+
X-Number: number
1151+
X-Array: array
1152+
X-Map: map
1153+
X-Boolean: boolean
1154+
X-Null: nulled
1155+
X-Text: text
11511156
forwardToken: false`,
1152-
Claims: `{"aud": "test", "user": "1234"}`,
1157+
Claims: `{"aud": "test", "number": "1234", "array": ["test", 1, null], "map": {"a": 1, "b": 2}, "boolean": true, "nulled": null, "text": "Hello, world!"}`,
11531158
Method: jwt.SigningMethodHS256,
11541159
HeaderName: "Authorization",
11551160
},

0 commit comments

Comments
 (0)