key-auth
is an authentication plugin, it should work with consumer
together.
Add Key Authentication (also sometimes referred to as an API key) to a Service or a Route. Consumers then add their key either in a querystring parameter or a header to authenticate their requests.
For consumer side:
Name | Type | Requirement | Default | Valid | Description |
---|---|---|---|---|---|
key | string | required | different consumer objects should use different values, it should be unique. |
For route side:
Name | Type | Requirement | Default | Valid | Description |
---|---|---|---|---|---|
header | string | optional | apikey | the header we get the key from | |
query | string | optional | apikey | the querystring we get the key from, which priority is lower than header |
Two steps are required:
key-auth
.curl http://127.0.0.1:9080/apisix/admin/consumers -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d ' { "username": "jack", "plugins": { "key-auth": { "key": "auth-one" } } }'
You can open dashboard with a browser: http://127.0.0.1:9080/apisix/dashboard/
, to complete the above operation through the web interface, first add a route:
Then add key-auth plugin:
key-auth
.curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d ' { "methods": ["GET"], "uri": "/index.html", "id": 1, "plugins": { "key-auth": {} }, "upstream": { "type": "roundrobin", "nodes": { "39.97.63.215:80": 1 } } }'
If you don't want to fetch key from the default apikey
header, you can customize the header:
{ "key-auth": { "header": "Authorization" } }
Here is a correct test example:
$ curl http://127.0.0.2:9080/index.html -H 'apikey: auth-one' -i HTTP/1.1 200 OK ...
If the request does not set apikey
correctly, will get a 401
response.
$ curl http://127.0.0.2:9080/index.html -i HTTP/1.1 401 Unauthorized ... {"message":"Missing API key found in request"} $ curl http://127.0.0.2:9080/index.html -H 'apikey: abcabcabc' -i HTTP/1.1 401 Unauthorized ... {"message":"Invalid API key in request"}
When you want to disable the key-auth
plugin, it is very simple, you can delete the corresponding json configuration in the plugin configuration, no need to restart the service, it will take effect immediately:
$ curl http://127.0.0.1:2379/v2/keys/apisix/routes/1 -X PUT -d value=' { "uri": "/index.html", "plugins": {}, "upstream": { "type": "roundrobin", "nodes": { "39.97.63.215:80": 1 } } }'
The key-auth
plugin has been disabled now. It works for other plugins.