Skip to content

Commit ff5ca46

Browse files
committed
Some Colin Notes
1 parent ba669e8 commit ff5ca46

File tree

6 files changed

+119
-125
lines changed

6 files changed

+119
-125
lines changed
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
---
2+
title: Machine-to-Machine Requests
3+
description: Learn how to use machine tokens to make and verify authenticated requests.
4+
---
5+
6+
## Introduction
7+
8+
Machine-to-machine (M2M) authentication allows services, scripts, or devices to securely communicate with each other without the need for a user's session.
9+
10+
For example, you might need machine tokens for:
11+
12+
- Cron jobs that update your database
13+
- Background workers processing queued tasks
14+
- Microservices communicati\@ng with each other
15+
16+
## Creating Machine Requests
17+
18+
If your client is a backend service, you can create a [machine token](/docs/machine-requests/machine-tokens) and use it in the `Authorization` header of outgoing request.
19+
20+
### Creating requests with the JavaScript Backend SDK
21+
22+
Use the `clerkClient.machineTokens` object to create a [machine token](/docs/machine-requests/machine-tokens), then use the created token to make authenticated requests.
23+
24+
> [!WARNING]
25+
> Creating machine tokens is subject to the [Backend API rate limits](/docs/backend-requests/resources/rate-limits)
26+
27+
```tsx
28+
import { createClerkClient } from '@clerk/backend'
29+
30+
export default async function cronJob() {
31+
const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })
32+
33+
const { token } = await clerkClient.machineTokens.create({
34+
machineId: 'mch_cron',
35+
claims: {
36+
permissions: ['read', 'write'],
37+
},
38+
expiresInSeconds: 60,
39+
})
40+
41+
await fetch('https://api.example.com/cron', {
42+
method: 'POST',
43+
headers: {
44+
Authorization: `Bearer ${token}`,
45+
},
46+
body: JSON.stringify({
47+
message: 'Hello World!',
48+
}),
49+
})
50+
}
51+
```
52+
53+
## Verifying Machine Requests
54+
55+
For a machine request to be valid, it must include a valid [machine token](/docs/machine-requests/machine-tokens) in the Bearer `Authorization` header.
56+
57+
You can verify machine tokens in two ways:
58+
59+
1. Using Clerk's Backend SDK (recommended)
60+
1. Manually verifying the JWT using your instance's public key.
61+
62+
### Verifying requests with the JavaScript Backend SDK
63+
64+
#### Using the `authenticateRequest()` method
65+
66+
You can use the `authenticateRequest()` method with the [JavaScript Backend SDK](/docs/references/backend/overview) to verify that the token is a valid machine token generated by Clerk.
67+
68+
```tsx
69+
import { createClerkClient } from '@clerk/backend'
70+
71+
export async function GET(req: Request) {
72+
const clerkClient = createClerkClient({
73+
secretKey: process.env.CLERK_SECRET_KEY,
74+
publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
75+
})
76+
77+
const { isMachineAuthenticated, machineId } = await clerkClient.authenticateRequest(req, {
78+
entity: 'machine',
79+
})
80+
81+
if (!isMachineAuthenticated) {
82+
return Response.json({ status: 401 })
83+
}
84+
85+
return Response.json({
86+
message: `Machine is authenticated with ID: ${machineId}`,
87+
})
88+
}
89+
```
90+
91+
#### Using the `await auth()` Next.js helper
92+
93+
You can use the `await auth()` Next.js helper to verify that the request is authenticated and that the user is a machine.
94+
95+
NOTE FOR REVIEWER:
96+
97+
> [!NOTE]
98+
> Currently the `auth()` helper does not support **any** parameters, adding the `entity` paramter would be a big change to the sdk.
99+
> I think we can add this and default to `entity: 'user'` -- but I am not confident here, so we probably want some back and forth on this.
100+
> Also, in the Next.js `auth()` function, will it know that the token is in the Authorization header? Not the cookie?
101+
102+
```tsx
103+
import { auth } from '@clerk/nextjs/server'
104+
105+
export async function GET() {
106+
const { isMachineAuthenticated, machineId } = await auth({ entity: 'machine' })
107+
108+
if (!isMachineAuthenticated) {
109+
return new Response('Machine authentication failed.', { status: 401 })
110+
}
111+
112+
return new Response(`Machine is authenticated with ID: ${machineId}`, { status: 200 })
113+
}
114+
```

docs/machine-requests/machine-tokens.mdx

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Every machine token you create needs to be associated with a `machine_id`. You c
1515

1616
- It must be prefixed with `mch_`
1717
- It must only contain lowercase letters and numbers
18-
- It must be 255 characters or less
18+
- It must be 96 characters or less
1919

2020
> [!TIP]
2121
> It is a good idea to have the `machine_id` correspond with the identity of the service generating the token. For example if you have a cron service, a `machine_id` of `mch_cron` would make sense.
@@ -60,10 +60,6 @@ Every generated token has default claims that cannot be overridden by custom cla
6060
- `nbf`: not before - the time before which the token is considered invalid, as a Unix timestamp. Determined using the **Allowed Clock Skew** request body parameter when creating machine tokens. See [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5) for more information.
6161
- `sub`: subject - the ID of the machine that created the token. Determined using the **Machine ID** request body parameter when creating machine tokens. For example: `mch_123`. See [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2) for more information.
6262

63-
## Making Machine Requests
63+
## Using Machine Tokens to create and verify requests
6464

65-
To start making machine requests, refer to [making machine requests](/docs/machine-requests/making).
66-
67-
## Validating Machine Tokens
68-
69-
To learn how to manually verify a machine token, refer to [validating machine tokens](/docs/machine-requests/verifying).
65+
To start using machine tokens to create and verify requests, refer to [making machine requests](/docs/machine-requests/machine-requests).

docs/machine-requests/making.mdx

Lines changed: 0 additions & 44 deletions
This file was deleted.

docs/machine-requests/overview.mdx

Lines changed: 0 additions & 20 deletions
This file was deleted.

docs/machine-requests/verifying.mdx

Lines changed: 0 additions & 44 deletions
This file was deleted.

docs/manifest.json

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -770,20 +770,12 @@
770770
"items": [
771771
[
772772
{
773-
"title": "Overview",
774-
"href": "/docs/machine-requests/overview"
773+
"title": "Machine requests",
774+
"href": "/docs/machine-requests/machine-requests"
775775
},
776776
{
777777
"title": "Machine tokens",
778778
"href": "/docs/machine-requests/machine-tokens"
779-
},
780-
{
781-
"title": "Making machine requests",
782-
"href": "/docs/machine-requests/making"
783-
},
784-
{
785-
"title": "Verifying machine requests",
786-
"href": "/docs/machine-requests/verifying"
787779
}
788780
]
789781
]

0 commit comments

Comments
 (0)