This example shows how to secure a Rust + Axum API using Unkey for API key management. You'll learn how to protect public and private routes with minimal setup and start authenticating users quickly.
- 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 https://app.unkey.com/apis and click on the "Create New API" button.
- Give it a name.
- Click "Create".
- Click "Create Key" in the top right corner.
- Feel the form with any key information you want or leave it empty.
- Click "Create"
- Copy the key and save it somewhere safe.
- Clone the repository to your local machine:
git clone git@github.com:unrenamed/unkey-rust-axum
cd unkey-rust-axum
- Create a
.env
file in the root directory and populate it with the following environment variables:
PORT=3000
UNKEY_ROOT_KEY=your-unkey-root-key
UNKEY_API_ID=your-unkey-api-id
Ensure you replace your-unkey-root-key
and your-unkey-api-id
with your actual Unkey credentials.
- Start the server:
cargo run
The server will start and listen on the port specified in the .env
file (default is 3000
).
- Test the public route as a guest:
curl http://localhost:3000/public
- Test the public route as an authorized user by passing the API key in the header:
curl http://localhost:3000/public -H "Authorization: Bearer <YOUR_API_KEY>"
- Test the protected route, which requires valid authorization:
curl http://localhost:3000/protected -H "Authorization: Bearer <YOUR_API_KEY>"