Skip to content

Commit

Permalink
Some Colin Notes
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben2W committed Dec 3, 2024
1 parent ba669e8 commit ff5ca46
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 125 deletions.
114 changes: 114 additions & 0 deletions docs/machine-requests/machine-requests.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
---
title: Machine-to-Machine Requests
description: Learn how to use machine tokens to make and verify authenticated requests.
---

## Introduction

Machine-to-machine (M2M) authentication allows services, scripts, or devices to securely communicate with each other without the need for a user's session.

For example, you might need machine tokens for:

- Cron jobs that update your database
- Background workers processing queued tasks
- Microservices communicati\@ng with each other

## Creating Machine Requests

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.

### Creating requests with the JavaScript Backend SDK

Use the `clerkClient.machineTokens` object to create a [machine token](/docs/machine-requests/machine-tokens), then use the created token to make authenticated requests.

> [!WARNING]
> Creating machine tokens is subject to the [Backend API rate limits](/docs/backend-requests/resources/rate-limits)
```tsx
import { createClerkClient } from '@clerk/backend'

export default async function cronJob() {
const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })

const { token } = await clerkClient.machineTokens.create({
machineId: 'mch_cron',
claims: {
permissions: ['read', 'write'],
},
expiresInSeconds: 60,
})

await fetch('https://api.example.com/cron', {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
message: 'Hello World!',
}),
})
}
```

## Verifying Machine Requests

For a machine request to be valid, it must include a valid [machine token](/docs/machine-requests/machine-tokens) in the Bearer `Authorization` header.

You can verify machine tokens in two ways:

1. Using Clerk's Backend SDK (recommended)
1. Manually verifying the JWT using your instance's public key.

### Verifying requests with the JavaScript Backend SDK

#### Using the `authenticateRequest()` method

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.

```tsx
import { createClerkClient } from '@clerk/backend'

export async function GET(req: Request) {
const clerkClient = createClerkClient({
secretKey: process.env.CLERK_SECRET_KEY,
publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
})

const { isMachineAuthenticated, machineId } = await clerkClient.authenticateRequest(req, {
entity: 'machine',
})

if (!isMachineAuthenticated) {
return Response.json({ status: 401 })
}

return Response.json({
message: `Machine is authenticated with ID: ${machineId}`,
})
}
```

#### Using the `await auth()` Next.js helper

You can use the `await auth()` Next.js helper to verify that the request is authenticated and that the user is a machine.

NOTE FOR REVIEWER:

> [!NOTE]
> Currently the `auth()` helper does not support **any** parameters, adding the `entity` paramter would be a big change to the sdk.
> 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.
> Also, in the Next.js `auth()` function, will it know that the token is in the Authorization header? Not the cookie?
```tsx
import { auth } from '@clerk/nextjs/server'

export async function GET() {
const { isMachineAuthenticated, machineId } = await auth({ entity: 'machine' })

if (!isMachineAuthenticated) {
return new Response('Machine authentication failed.', { status: 401 })
}

return new Response(`Machine is authenticated with ID: ${machineId}`, { status: 200 })
}
```
10 changes: 3 additions & 7 deletions docs/machine-requests/machine-tokens.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Every machine token you create needs to be associated with a `machine_id`. You c

- It must be prefixed with `mch_`
- It must only contain lowercase letters and numbers
- It must be 255 characters or less
- It must be 96 characters or less

> [!TIP]
> 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.
Expand Down Expand Up @@ -60,10 +60,6 @@ Every generated token has default claims that cannot be overridden by custom cla
- `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.
- `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.

## Making Machine Requests
## Using Machine Tokens to create and verify requests

To start making machine requests, refer to [making machine requests](/docs/machine-requests/making).

## Validating Machine Tokens

To learn how to manually verify a machine token, refer to [validating machine tokens](/docs/machine-requests/verifying).
To start using machine tokens to create and verify requests, refer to [making machine requests](/docs/machine-requests/machine-requests).
44 changes: 0 additions & 44 deletions docs/machine-requests/making.mdx

This file was deleted.

20 changes: 0 additions & 20 deletions docs/machine-requests/overview.mdx

This file was deleted.

44 changes: 0 additions & 44 deletions docs/machine-requests/verifying.mdx

This file was deleted.

12 changes: 2 additions & 10 deletions docs/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -770,20 +770,12 @@
"items": [
[
{
"title": "Overview",
"href": "/docs/machine-requests/overview"
"title": "Machine requests",
"href": "/docs/machine-requests/machine-requests"
},
{
"title": "Machine tokens",
"href": "/docs/machine-requests/machine-tokens"
},
{
"title": "Making machine requests",
"href": "/docs/machine-requests/making"
},
{
"title": "Verifying machine requests",
"href": "/docs/machine-requests/verifying"
}
]
]
Expand Down

0 comments on commit ff5ca46

Please sign in to comment.