Skip to content

Commit f041fc8

Browse files
committed
#71 Skip basic auth for OPTIONS http method
The OPTIONS needed for CORS requests Signed-off-by: Sergey Ponomarev <[email protected]>
1 parent 48868f5 commit f041fc8

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

web/handler.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,8 @@ func (u *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
9797
w.Header().Set(k, v)
9898
}
9999

100-
if len(c.Users) == 0 {
100+
// If OPTIONS method or none users configured then skip auth check
101+
if r.Method == http.MethodOptions || len(c.Users) == 0 {
101102
u.handler.ServeHTTP(w, r)
102103
return
103104
}

web/handler_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,3 +172,47 @@ func TestHTTPHeaders(t *testing.T) {
172172
}
173173
}
174174
}
175+
176+
// TestBasicAuthIsNotNeededForMethodOptions validates that OPTIONS method is always allowed
177+
func TestBasicAuthIsNotNeededForMethodOptions(t *testing.T) {
178+
server := &http.Server{
179+
Addr: port,
180+
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
181+
if r.Method == http.MethodOptions {
182+
w.Header().Set("Access-Control-Allow-Origin", "https://example.com:8080")
183+
w.Header().Set("Access-Control-Expose-Headers", "Date")
184+
w.Header().Set("Access-Control-Allow-Methods", "GET,OPTIONS,POST")
185+
w.Header().Set("Access-Control-Allow-Headers", "Accept,Authorization,Date,Content-Type,Origin")
186+
w.Header().Set("Access-Control-Allow-Credentials", "true")
187+
w.WriteHeader(http.StatusNoContent)
188+
}
189+
w.WriteHeader(http.StatusMethodNotAllowed)
190+
}),
191+
}
192+
193+
done := make(chan struct{})
194+
t.Cleanup(func() {
195+
if err := server.Shutdown(context.Background()); err != nil {
196+
t.Fatal(err)
197+
}
198+
<-done
199+
})
200+
201+
go func() {
202+
ListenAndServe(server, "testdata/web_config_users_noTLS.good.yml", testlogger)
203+
close(done)
204+
}()
205+
206+
client := &http.Client{}
207+
req, err := http.NewRequest("OPTIONS", "http://localhost"+port, nil)
208+
if err != nil {
209+
t.Fatal(err)
210+
}
211+
r, err := client.Do(req)
212+
if err != nil {
213+
t.Fatal(err)
214+
}
215+
if r.StatusCode != 204 {
216+
t.Fatalf("bad return code, expected %d, got %d", 204, r.StatusCode)
217+
}
218+
}

0 commit comments

Comments
 (0)