@@ -85,35 +85,27 @@ func (mgr *Manager) Register(mux *http.ServeMux) error {
8585}
8686
8787func (mgr * Manager ) Handler (next http.Handler ) http.Handler {
88- htmlHandler := htmlresponse .NewHandler (mgr .config )
88+ htmlHandler := htmlresponse .NewHandler (mgr .config , true )
8989 return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
9090 rawToken :=
9191 strings .TrimSpace (strings .TrimPrefix (strings .TrimSpace (r .Header .Get ("Authorization" )), "Bearer" ))
92-
93- shouldCallNext := true
94-
95- token , err := jwt .ParseString (rawToken , jwt .WithKeySet (mgr .jwkSet ))
96- if err != nil {
97- metadataURL , _ := url .Parse (mgr .config .Host .String ())
98- metadataURL .Path = ProtectedResourcePath
99- metadataURL = metadataURL .JoinPath (r .URL .Path )
100- w .Header ().Set (
101- "WWW-Authenticate" ,
102- fmt .Sprintf (`Bearer resource_metadata="%s"` , metadataURL .String ()),
103- )
104- w .WriteHeader (http .StatusUnauthorized )
105- shouldCallNext = false
106- }
107-
108- if strings .Contains (r .Header .Get ("Accept" ), "text/html" ) {
109- if err := htmlHandler .Handle (w , r ); err != nil {
110- log .Get (r .Context ()).Error (err , "failed to handle html response" )
111- }
112- shouldCallNext = false
113- }
114-
115- if shouldCallNext {
92+ if token , err := jwt .ParseString (rawToken , jwt .WithKeySet (mgr .jwkSet )); err != nil {
93+ htmlHandler .Handler (mgr .unauthorizedHandler ()).ServeHTTP (w , r )
94+ } else {
11695 next .ServeHTTP (w , r .WithContext (TokenContext (r .Context (), token , rawToken )))
11796 }
11897 })
11998}
99+
100+ func (mgr * Manager ) unauthorizedHandler () http.HandlerFunc {
101+ return func (w http.ResponseWriter , r * http.Request ) {
102+ metadataURL , _ := url .Parse (mgr .config .Host .String ())
103+ metadataURL .Path = ProtectedResourcePath
104+ metadataURL = metadataURL .JoinPath (r .URL .Path )
105+ w .Header ().Set (
106+ "WWW-Authenticate" ,
107+ fmt .Sprintf (`Bearer resource_metadata="%s"` , metadataURL .String ()),
108+ )
109+ w .WriteHeader (http .StatusUnauthorized )
110+ }
111+ }
0 commit comments