Hello everyone. Newbie here!
My company is looking into using Kong and I’ve been tasked with doing some research. After digging through the Kong and Key-Auth docs, I’m not able to find an answer to my current question.
Is it possible to return a different HTTP code than 403 if you try to send a request without the proper API key header? For example, how would I return a 401?
Thanks!
Hi,
If an API key is not found in the request, Kong will return a 401:
elseif type(v) == "table" then
-- duplicate API key
return nil, { status = 401, message = "Duplicate API key found" }
end
end
-- this request is missing an API key, HTTP 401
if not key or key == "" then
kong.response.set_header("WWW-Authenticate", _realm)
return nil, { status = 401, message = "No API key found in request" }
end
-- retrieve our consumer linked to this API key
local cache = kong.cache
local credential_cache_key = kong.db.keyauth_credentials:cache_key(key)
local credential, err = cache:get(credential_cache_key, nil, load_credential,
key)
if err then
And if the presented API key is not found to be configured in the Kong cluster, Kong will also respond with a 401 as well:
local credential_cache_key = kong.db.keyauth_credentials:cache_key(key)
local credential, err = cache:get(credential_cache_key, nil, load_credential,
key)
if err then
kong.log.err(err)
return kong.response.exit(500, "An unexpected error occurred")
end
-- no credential in DB, for this key, it is invalid, HTTP 401
if not credential then
return nil, { status = 401, message = "Invalid authentication credentials" }
end
-----------------------------------------
-- Success, this request is authenticated
-----------------------------------------
-- retrieve the consumer linked to this API key, to set appropriate headers
local consumer_cache_key, consumer
consumer_cache_key = kong.db.consumers:cache_key(credential.consumer.id)
consumer, err = cache:get(consumer_cache_key, nil, load_consumer,
HTH!