Allowing Multiple Authentication Methods

    To begin, create a Service and then create three consumers:

    The consumer does not correspond to any real user, and will only serve as a fallback.

    1. curl -sX POST kong-admin:8001/services/example-service/plugins/ \
    2. -H "Content-Type: application/json" \
    3. --data '{"name": "key-auth", "config": { "hide_credentials": true, "anonymous": "d955c0cb-1a6e-4152-9440-414ebb8fee8a"} }'
    4. # {"created_at":1517528304000,"config":{"key_in_body":false,"hide_credentials":true,"anonymous":"d955c0cb-1a6e-4152-9440-414ebb8fee8a","run_on_preflight":true,"key_names":["apikey"]},"id":"bb884f7b-4e48-4166-8c80-c858b5a4c357","name":"key-auth","service_id":"a2a168a8-4491-4fe1-9426-cde3b5fcd45b","enabled":true}
    5. curl -sX POST kong-admin:8001/services/example-service/plugins/ \
    6. -H "Content-Type: application/json" \
    7. --data '{"name": "basic-auth", "config": { "hide_credentials": true, "anonymous": "d955c0cb-1a6e-4152-9440-414ebb8fee8a"} }'
    8. # {"created_at":1517528499000,"config":{"hide_credentials":true,"anonymous":"d955c0cb-1a6e-4152-9440-414ebb8fee8a"},"id":"e5a40543-debe-4225-a879-a54901368e6d","name":"basic-auth","service_id":"a2a168a8-4491-4fe1-9426-cde3b5fcd45b","enabled":true}

    If using , you must also set config.consumer_claim along with , as setting anonymous alone will not map that consumer.

    At this point unauthenticated requests and requests with invalid credentials are still allowed. The anonymous consumer is allowed, and will be applied to any request that does not pass a set of credentials associated with some other consumer.

    1. -H "Content-Type: application/json" \
    2. --data '{"username": "medvezhonok", "password": "hunter2"}'
    3. # {"created_at":1517528647000,"id":"bb350b87-f0d2-4605-b997-e28a116d8b6d","username":"medvezhonok","password":"f239a0404351d7170201e7f92fa9b3159e47bb01","consumer_id":"b3c95318-a932-4bb2-9d74-1298a3ffc87c"}
    4. curl -sX POST kong-admin:8001/consumers/ezhik/key-auth \
    5. -H "Content-Type: application/json" \
    6. --data '{"key": "hunter3"}'
    7. # {"id":"06412d6e-8d41-47f7-a911-3c821ec98f1b","created_at":1517528730000,"key":"hunter3","consumer_id":"47e74a17-dc08-4786-a8cf-d8e4f38a5459"}

    Lastly, we add a Request Terminator to the anonymous consumer.

    Requests with missing or invalid credentials are now rejected, whereas authorized requests using either authentication method are allowed.

    1. # {"error": "Authentication required"}
    2. curl -s example.com:8000/user-agent
    3. # {"error": "Authentication required"}
    4. curl -s example.com:8000/user-agent?apikey=hunter3
    5. # {"user-agent": "curl/7.58.0"}
    6. curl -s example.com:8000/user-agent -u medvezhonok:hunter2
    7. # {"user-agent": "curl/7.58.0"}