# API Key Authentication Policy

You can learn more about the Zuplo API Key Service
[in our documentation](https://zuplo.com/docs/articles/api-key-api#buckets)

Authenticate requests with Zuplo's fully managed API Key service. This policy is
the easiest way to secure your API and can be combined with other policies like
Rate limiting, quotas, and more to build a fully featured API to support your
partners, developers, or customers.

With this policy, you'll benefit from:

- **Simplified Authentication**: Implement API key authentication in minutes
  with zero code
- **Enhanced Security**: Protect your APIs with robust key validation and
  management
- **Developer-Friendly Experience**: Provide an intuitive way for consumers to
  authenticate with your API
- **Complete Management Solution**: Create, revoke, and rotate API keys through
  Zuplo's built-in management portal
- **Flexible Implementation**: Support multiple authentication methods including
  header, query parameter, or cookie
- **Granular Access Control**: Assign custom metadata and permissions to
  different API keys
- **Analytics Integration**: Track API key usage and monitor consumption
  patterns

For more information on Zuplo's API Key Management service and options enabling
self-serve API Key management see the following resources:

- [API Key Authentication Overview](https://zuplo.com/docs/articles/api-key-management)
- [API Key Management API](https://zuplo.com/docs/articles/api-key-api)

## Configuration

The configuration shows how to configure the policy in the 'policies.json' document.

```json title="config/policies.json"
{
  "name": "my-api-key-inbound-policy",
  "policyType": "api-key-inbound",
  "handler": {
    "export": "ApiKeyInboundPolicy",
    "module": "$import(@zuplo/runtime)",
    "options": {
      "allowUnauthenticatedRequests": false,
      "cacheTtlSeconds": 60
    }
  }
}
```

### Policy Configuration

- `name` <code className="text-green-600">&lt;string&gt;</code> - The name of your policy instance. This is used as a reference in your routes.
- `policyType` <code className="text-green-600">&lt;string&gt;</code> - The identifier of the policy. This is used by the Zuplo UI. Value should be `api-key-inbound`.
- `handler.export` <code className="text-green-600">&lt;string&gt;</code> - The name of the exported type. Value should be `ApiKeyInboundPolicy`.
- `handler.module` <code className="text-green-600">&lt;string&gt;</code> - The module containing the policy. Value should be `$import(@zuplo/runtime)`.
- `handler.options` <code className="text-green-600">&lt;object&gt;</code> - The options for this policy. [See Policy Options](#policy-options) below.

### Policy Options

The options for this policy are specified below. All properties are optional unless specifically marked as required.

- `authHeader` <code className="text-green-600">&lt;string&gt;</code> - The name of the header with the key. Defaults to `"Authorization"`.
- `authScheme` <code className="text-green-600">&lt;string&gt;</code> - The scheme used on the header. Defaults to `"Bearer"`.
- `bucketName` <code className="text-green-600">&lt;string&gt;</code> - The name of the API Key service bucket. Defaults to the autogenerated bucket name for your project.
- `allowUnauthenticatedRequests` <code className="text-green-600">&lt;boolean&gt;</code> - If requests should proceed even if the policy does not successfully authenticate the request. Defaults to false and rejects any request without a valid API key (returning a `401 - Unauthorized` response). Set to `true` to support multiple authentication methods or support both authenticated and anonymous requests. Defaults to `false`.
- `cacheTtlSeconds` <code className="text-green-600">&lt;number&gt;</code> - The time to cache authentication results for a particular key. Higher values will decrease latency. Cached results will be valid until the cache expires even in the event the key is deleted, etc. Defaults to `60`.
- `disableAutomaticallyAddingKeyHeaderToOpenApi` <code className="text-green-600">&lt;boolean&gt;</code> - Zuplo will automatically document your API key header within your OpenAPI specification &amp; Developer Portal. Set this to `true` to disable this behavior.

## Using the Policy

Adding API Key authentication to your Zuplo API takes only a few minutes. This
document shows you how to add the policy to your routes, create an API key, and
make a request using the API Key.

## Add the API Key Policy

The first step to setting up API Key authentication is to add the API
Authentication policy to a route in your project.

1. In the [Zuplo Portal](https://portal.zuplo.com) open the **Route Designer**
   in the **Files** tab then click **routes.oas.json**.

2. Select or create a route that you want to authenticate with API Keys. Expand
   the **Policies** section and click **Add Policy**. Search for and select the
   API Key Inbound policy.

   <Screenshot src="https://cdn.zuplo.com/assets/1a35f4e6-9309-4f22-89da-2e2c25e68403.png" />

3. With the policy selected, you will see the configuration and information
   about the options. For this tutorial just leave the options as they are and
   click **OK** to save the policy.

   <Screenshot src="https://cdn.zuplo.com/assets/736fad78-37c8-4f12-9e58-8e697a14284c.png" />

## Create an API Key

In order to make a request to the route, you'll need an API Key.

1. In the [Zuplo Portal](https://portal.zuplo.com) open the **API Key
   Consumers** section in the **Settings** tab.

2. Click the button **Add New Consumer**.

3. In the form that appears, enter a value for the **Subject** such as
   `my-test`. You can leave the other fields empty. Click **OK** to create the
   consumer.

   <Screenshot
     src="https://cdn.zuplo.com/assets/68b4571d-fcbc-4c92-977f-7612cd0cfb32.png"
     size="md"
   />

4. Now you can see the newly created consumer and its default API key. Select
   the **Copy** button to copy the API Key. You will use this value in the next
   section.

<Screenshot
  src="https://cdn.zuplo.com/assets/98a3d62f-1b61-4f41-8bac-665e0b02309e.png"
  size="lg"
/>

### Test the Policy

Finally, you'll make two API requests to your route to test that authentication
is working as expected.

1. In the route designer on the route you added the policy, click the **Test**
   button. In the dialog that opens, click **Test** to make a request.

2. The API Gateway should respond with a **401 Unauthorized** response.

<Screenshot
  src="https://cdn.zuplo.com/assets/626e10a2-2350-439a-9081-1ccf1fe90cad.png"
  size="md"
/>

3. Now to make an authenticated request, add a header to the request called
   `Authorization`. Set the value of the header to `Bearer YOUR_API_KEY`
   replacing `YOUR_API_KEY` with the value of the API Key you copied in the
   previous section.

<Screenshot
  src="https://cdn.zuplo.com/assets/11a3f88a-8613-43c9-9429-4c82e1f1ab4d.png"
  size="lg"
/>

4. Click the **Test** button and a **200 OK** response should be returned.

<Screenshot
  src="https://cdn.zuplo.com/assets/8182f932-8db6-4456-842f-f65158b174c0.png"
  size="md"
/>

You have now setup API Key Authentication on your API Gateway.

See [this document](/docs/articles/api-key-management) for more information
about API Keys and API Key Management with Zuplo.

## Writing Tests with the Auth Policy

For information on running tests while using API Key Authentication see the
document
[Testing API Key Authentication](/docs/articles/testing-api-key-authentication).

Read more about [how policies work](/articles/policies)
