@@ -17,6 +17,8 @@ import (
17
17
"github.com/golang-jwt/jwt/v5"
18
18
)
19
19
20
+ const functionRealm = "IAM function invoke"
21
+
20
22
func NewJWTAuthMiddleware (next http.Handler ) (http.Handler , error ) {
21
23
var authority = "http://gateway.openfaas:8080/.well-known/openid-configuration"
22
24
if v , ok := os .LookupEnv ("jwt_auth_local" ); ok && (v == "true" || v == "1" ) {
@@ -71,7 +73,7 @@ func NewJWTAuthMiddleware(next http.Handler) (http.Handler, error) {
71
73
}
72
74
73
75
if bearer == "" {
74
- http . Error (w , "Bearer must be present in Authorization header" , http . StatusUnauthorized )
76
+ httpUnauthorized (w , "Bearer must be present in Authorization header" )
75
77
log .Printf ("%s %s - %d ACCESS DENIED - (%s)" , r .Method , r .URL .Path , http .StatusUnauthorized , time .Since (st ).Round (time .Millisecond ))
76
78
return
77
79
}
@@ -108,14 +110,13 @@ func NewJWTAuthMiddleware(next http.Handler) (http.Handler, error) {
108
110
return key .Key .(crypto.PublicKey ), nil
109
111
}, parseOptions ... )
110
112
if err != nil {
111
- http .Error (w , fmt .Sprintf ("failed to parse JWT token: %s" , err ), http .StatusUnauthorized )
112
-
113
+ httpUnauthorized (w , fmt .Sprintf ("failed to parse JWT token: %s" , err ))
113
114
log .Printf ("%s %s - %d ACCESS DENIED - (%s)" , r .Method , r .URL .Path , http .StatusUnauthorized , time .Since (st ).Round (time .Millisecond ))
114
115
return
115
116
}
116
117
117
118
if ! token .Valid {
118
- http . Error (w , fmt .Sprintf ("invalid JWT token: %s" , bearer ), http . StatusUnauthorized )
119
+ httpUnauthorized (w , fmt .Sprintf ("invalid JWT token: %s" , bearer ))
119
120
120
121
log .Printf ("%s %s - %d ACCESS DENIED - (%s)" , r .Method , r .URL .Path , http .StatusUnauthorized , time .Since (st ).Round (time .Millisecond ))
121
122
return
@@ -132,6 +133,15 @@ func NewJWTAuthMiddleware(next http.Handler) (http.Handler, error) {
132
133
}), nil
133
134
}
134
135
136
+ // httpUnauthorized replies to the request with the specified error message and 401 HTTP code.
137
+ // It sets the WWW-Authenticate header.
138
+ // It does not otherwise end the request; the caller should ensure no further writes are done to w.
139
+ // The error message should be plain text.
140
+ func httpUnauthorized (w http.ResponseWriter , err string ) {
141
+ w .Header ().Set ("WWW-Authenticate" , fmt .Sprintf ("Bearer realm=%s" , functionRealm ))
142
+ http .Error (w , err , http .StatusUnauthorized )
143
+ }
144
+
135
145
func getKeyset (uri string ) (jwk.KeySpecSet , error ) {
136
146
var set jwk.KeySpecSet
137
147
req , err := http .NewRequest (http .MethodGet , uri , nil )
0 commit comments