|
| 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 | +``` |
0 commit comments