|
| 1 | +--- |
| 2 | +title: Testing API Key Authentication |
| 3 | +--- |
| 4 | + |
| 5 | +When running tests there are several ways you might want to handle API Key |
| 6 | +authentication. This document outlines a few strategies for testing with API Key |
| 7 | +authentication both locally and in deployed environments. |
| 8 | + |
| 9 | +## Testing Locally |
| 10 | + |
| 11 | +When running API key Authentication locally, if you |
| 12 | +[link](/docs/cli/local-development) the project to an project the same API Key |
| 13 | +Bucket used in working copy will also be used for local development. |
| 14 | + |
| 15 | +Alternatively, you can specify any API Key Bucket on the |
| 16 | +[API Key Authentication](/docs/policies/api-key-inbound) policy by setting the |
| 17 | +`bucketName` property. |
| 18 | + |
| 19 | +## Selectively Disabling |
| 20 | + |
| 21 | +:::danger |
| 22 | + |
| 23 | +Be extremely careful using this strategy. If configured incorrectly this could |
| 24 | +leave your API open to unauthorized access. |
| 25 | + |
| 26 | +::: |
| 27 | + |
| 28 | +Another option is to disable authentication on endpoints for testing purposes. |
| 29 | +One way of doing this is to configure the |
| 30 | +[API Key Authentication](/docs/policies/api-key-inbound) policy to allow |
| 31 | +unauthenticated requests through. This can be done by setting |
| 32 | +`allowUnauthenticatedRequests` to true. |
| 33 | + |
| 34 | +In order to enforce authentication with this setting disabled, you can create a |
| 35 | +policy that comes after that selectively enforces auth based on some condition. |
| 36 | + |
| 37 | +For example, an environment variable flag could be used to disable auth with the |
| 38 | +following policy. |
| 39 | + |
| 40 | +```ts |
| 41 | +import { |
| 42 | + ZuploContext, |
| 43 | + ZuploRequest, |
| 44 | + environment, |
| 45 | + HttpProblems, |
| 46 | +} from "@zuplo/runtime"; |
| 47 | + |
| 48 | +export default async function enforceAuth( |
| 49 | + request: ZuploRequest, |
| 50 | + context: ZuploContext, |
| 51 | +) { |
| 52 | + if (environment.DISABLE_AUTH === "AUTH_DISABLED") { |
| 53 | + return request; |
| 54 | + } |
| 55 | + |
| 56 | + if (!request.user) { |
| 57 | + return HttpProblems.unauthorized(request, context); |
| 58 | + } |
| 59 | + |
| 60 | + return request; |
| 61 | +} |
| 62 | +``` |
0 commit comments