This guide demonstrates how to protect your Feathers app using a custom authentication strategy built around the Unkey for managing and validating API keys. By leveraging Unkey's API key validation system, we can ensure that requests to your Feathers backend are authenticated using time-sensitive, secure keys.
- Feathers JS: An open source framework for building APIs and real-time applications.
- Unkey: A service to manage API keys with advanced features like time-bound access, rate limiting, and access control.
- Secure endpoints with both Local Auth and API Key-based strategies.
- Integration with Unkey API to validate keys for time-sensitive access.
Within the custom API key auth strategy, we'll check if there is a specific header in the request containing a valid API key. If true, we'll successfully authorize the request.
- Go to settings.root-keys and click on the "Create New Root Key" button.
- Enter a name for the key.
- Select the following workspace permissions:
create_key
,read_key
,encrypt_key
anddecrypt_key
. - Click "Create".
- Go to apis and click on the "Create New API" button.
- Give it a name.
- Click "Create".
-
Clone the repository
git clone git@github.com:unrenamed/unkey-feathers cd unkey-feathers
-
Install your dependencies
pnpm install
-
Create a
.env.local
file and add the following:UNKEY_ROOT_KEY=your-root-key UNKEY_API_ID=your-api-id
-
Start your app
pnpm compile # Compile TypeScript source pnpm migrate # Run migrations to set up the database pnpm start
The server will start and listen on
3030
port.
-
Create some users before accesing
GET
endpointcurl -X POST http://localhost:3030/users \ -H "Content-Type: application/json" \ -d '{ "email": "alice@unkey.com", "password": "supersecret" }'
-
Validate if you can access
/users
and/users/:id
endpointscurl -X GET http://localhost:3030/users curl -X GET http://localhost:3030/users/1
These two are protected. You should NOT be able to access them before authorization.
-
Authorize using
local
strategy, i.e. email + passwordcurl -X POST http://localhost:3030/authentication \ -H "Content-Type: application/json" \ -d '{ "email": "alice@unkey.com", "password": "supersecret", "strategy": "local" }'
-
Validate if you can access
/users
and/users/:id
endpointscurl -X GET http://localhost:3030/users \ -H "Authorization: Bearer <your-bearer-token>"
curl -X GET http://localhost:3030/users/:id \ -H "Authorization: Bearer <your-bearer-token>"
The first one still not accessible, because it requires an API key for access.
-
Create an API key to access routes protected with API key strategy
curl -X POST http://localhost:3030/keys \ -H "Content-Type: application/json" \ -d '{}'
You will get
key
andkeyId
in the response object. -
Now you can access
/users
route withx-api-key
header and valid keycurl -X GET http://localhost:3030/users \ -H 'Content-Type: application/json' \ -H 'x-api-key: <your-api-key>'