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:
+12
-1
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user