lib/api: Allow Bearer authentication style with API key (#9002)

Currently, historically, we look for the `X-API-Key` header to
authenticate with an API key. There's nothing wrong with this, but in
some scenarios it's easier to produce an `Authorization` header with a
`Bearer $token` content, which is nowadays more common. This change adds
support for both, so that we will accept an API key either in our custom
header or as a bearer token.
This commit is contained in:
Jakob Borg
2023-07-26 13:13:06 +02:00
committed by GitHub
parent dc5e10fa2c
commit 855c6dc67b
3 changed files with 199 additions and 81 deletions
+12 -1
View File
@@ -59,7 +59,7 @@ func newCsrfManager(unique string, prefix string, apiKeyValidator apiKeyValidato
func (m *csrfManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Allow requests carrying a valid API key
if m.apiKeyValidator.IsValidAPIKey(r.Header.Get("X-API-Key")) {
if hasValidAPIKeyHeader(r, m.apiKeyValidator) {
// Set the access-control-allow-origin header for CORS requests
// since a valid API key has been provided
w.Header().Add("Access-Control-Allow-Origin", "*")
@@ -178,3 +178,14 @@ func (m *csrfManager) load() {
m.tokens = append(m.tokens, s.Text())
}
}
func hasValidAPIKeyHeader(r *http.Request, validator apiKeyValidator) bool {
if key := r.Header.Get("X-API-Key"); validator.IsValidAPIKey(key) {
return true
}
if auth := r.Header.Get("Authorization"); strings.HasPrefix(strings.ToLower(auth), "bearer ") {
bearerToken := auth[len("bearer "):]
return validator.IsValidAPIKey(bearerToken)
}
return false
}