parse HTTP username and password OR token, not both (#4517)

This commit is contained in:
Alessandro Ros
2025-05-11 10:20:57 +02:00
committed by GitHub
parent f97213ae6e
commit c17a6de2a6
2 changed files with 31 additions and 6 deletions
+13 -6
View File
@@ -11,16 +11,23 @@ import (
func Credentials(h *http.Request) *auth.Credentials {
c := &auth.Credentials{}
c.User, c.Pass, _ = h.BasicAuth()
for _, auth := range h.Header["Authorization"] {
if strings.HasPrefix(auth, "Bearer ") {
// user:pass in Authorization Bearer
if parts := strings.Split(auth[len("Bearer "):], ":"); len(parts) == 2 {
c.User = parts[0]
c.Pass = parts[1]
return c
}
if auth := h.Header.Get("Authorization"); strings.HasPrefix(auth, "Bearer ") {
if parts := strings.Split(auth[len("Bearer "):], ":"); len(parts) == 2 { // user:pass in Authorization Bearer
c.User = parts[0]
c.Pass = parts[1]
} else { // JWT in Authorization Bearer
// JWT in Authorization Bearer
c.Token = auth[len("Bearer "):]
return c
}
}
// user:pass in Authorization Basic
c.User, c.Pass, _ = h.BasicAuth()
return c
}
@@ -62,4 +62,22 @@ func TestCredentials(t *testing.T) {
Token: "testing123",
}, c)
})
t.Run("user and pass and token", func(t *testing.T) {
h := &http.Request{
URL: &url.URL{},
Header: http.Header{
"Authorization": []string{
"Basic bXl1c2VyOm15cGFzcw==",
"Bearer testing123",
},
},
}
c := Credentials(h)
require.Equal(t, &auth.Credentials{
Token: "testing123",
}, c)
})
}