Skip to content

Commit

Permalink
adding manual jwt verification
Browse files Browse the repository at this point in the history
improving authenticateRequest docs page

updating auth object type

editing nextjs auth docs page

Removing unnecessary preface
  • Loading branch information
Ben2W committed Feb 7, 2025
1 parent 9529cf1 commit c7a9659
Show file tree
Hide file tree
Showing 7 changed files with 262 additions and 59 deletions.
2 changes: 1 addition & 1 deletion docs/machine-requests/machine-tokens.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: Learn about machine tokens and how to validate them in your backend

**Machine tokens** are JWTs used to authenticate machine requests your application makes.

Unlike [session tokens](/docs/session-requests/session-tokens), machine tokens are not associated with a user or session. Instead **you** are responsible for determining the identity of the machine making the request.
They are similiar to [session tokens](/docs/session-requests/session-tokens) however, unlike session tokens, machine tokens are not associated with a user. Instead __you__ are responsible for determining the identity of the machine making the request.

## Creating machine tokens

Expand Down
134 changes: 134 additions & 0 deletions docs/machine-requests/manual-jwt.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
---
title: Manual JWT verification
description: Learn how to manually verify Clerk-generated machine tokens (JWTs).
---

Your Clerk-generated [machine tokens](/docs/machine-requests/machine-tokens) are essentially JWTs which are signed using your instance's private key and can be verified using your instance's public key.

For every machine request, you must validate the token to ensure it hasn't expired or been tampered with (i.e., it's authentic and secure). Additionally, you likely want to differentiate between machine and user requests. If these validations succeed, then the machine is authenticated to your application.

> [!TIP]
> To differentiate between a machine token and user token, the `sub` claim in a machine token starts with `mch_` instead of `user_` on a session token.
The `authenticateRequest()` method from the JavaScript Backend SDK handles these validations for you. Alternatively, you can manually verify the token without using the SDK. See the following sections for more information.

## Use `authenticateRequest()` to verify a machine token

The [`authenticateRequest()`](/docs/references/backend/authenticate-request) method from the JavaScript Backend SDK accepts the `request` object, and by using the `entity: "machine"` option, you can authenticate the request *as a machine request* instead of the default *user request*.

For more information, including usage with higher-level SDKs, see the [`authenticateRequest()` reference](/docs/references/backend/authenticate-request).

For example, the following code snippet uses the `authenticateRequest()` method to verify a machine token in a simple node http server.

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

const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY });

const server = http.createServer(async (req, res) => {
try {
const { isMachineAuthenticated } = await clerk.authenticateRequest(req, {
entity: 'machine',
});

if (!isMachineAuthenticated) {
res.writeHead(401);
res.end(JSON.stringify({ message: 'Unauthorized' }));
return;
}

await runCronJob();

res.writeHead(200);
res.end(JSON.stringify({ message: 'Success' }));
} catch (err) {
res.writeHead(500);
res.end(JSON.stringify({ message: 'Internal Server Error' }));
}
});

server.listen(3000, () => {
console.log('Server running on port 3000');
});
```


## Manually verify a machine token

<Steps>
### Retrieve the machine token

Retrieve the machine token from the `Authorization` header.

### Get your instance's public key

Use one of the three ways to obtain your public key:

1. Use the Backend API in JSON Web Key Set (JWKS) format at the following endpoint [https://api.clerk.com/v1/jwks](https://clerk.com/docs/reference/backend-api/tag/JWKS#operation/GetJWKS).
1. Use your **Frontend API URL** in JWKS format, also known as **JWKS URL**. The format is `https://<YOUR_FRONTEND_API>/.well-known/jwks.json`. To retrieve your **JWKS URL**, navigate to the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard and select **Show JWT public key**.
1. Use your **PEM Public Key**. To retrieve it, navigate to the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard and select **Show JWT Public Key**.

### Verify the token signature

To verify the token signature:

1. Use your instance's public key to verify the token's signature.
1. Validate that the token isn't expired by checking the `exp` ([expiration time](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4)) and `nbf` ([not before](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5)) claims.
1. Validate that the `sub` (subject) claim starts with `mch_`. This ensures the token is a machine token and not a session token.

### Finished

If the above process succeeds, the machine is considered authenticated to make requests to your application. You can also retrieve the machine ID from the token's `sub` claim.
</Steps>

### Example

The following example manually verifies a machine token.

```tsx
import jwt from 'jsonwebtoken'

export default async function (req: Request, res: Response) {
// Your public key should be set as an environment variable
const publicKey = process.env.CLERK_PEM_PUBLIC_KEY

// Get the machine token from the Authorization header
const authHeader = req.headers.authorization
if (!authHeader) {
res.status(401).json({ error: 'No machine token provided' })
return
}

// Remove 'Bearer ' prefix if present
const token = authHeader.replace('Bearer ', '')

try {
const options = { algorithms: ['RS256'] }
const decoded = jwt.verify(token, publicKey, options)

// Validate the token's expiration (exp) and not before (nbf) claims
const currentTime = Math.floor(Date.now() / 1000)
if (decoded.exp < currentTime || decoded.nbf > currentTime) {
throw new Error('Token is expired or not yet valid')
}

// Validate that this is a machine token by checking the sub claim
if (!decoded.sub?.startsWith('mch_')) {
throw new Error('Not a valid machine token')
}

// The machine is authenticated. You can get the machine ID from the sub claim
const machineId = decoded.sub

res.status(200).json({
machineId,
claims: decoded
})
} catch (error) {
res.status(401).json({
error: error.message,
})
}
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ 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:
Expand All @@ -15,7 +13,7 @@ For example, you might need machine tokens for:

## Creating Machine Requests

If your client is a backend service, you can create a machine token using the [clerk backend api](https://clerk.com/docs/reference/backend-api/tag/machine-tokens). Then use the created token in the `Authorization` header of outgoing request.
You can create a machine token using the [clerk backend api](https://clerk.com/docs/reference/backend-api/tag/machine-tokens). Then use the created token in the `Authorization` header of outgoing request.

> [!WARNING]
> Because creating machine tokens using [clerk backend api](https://clerk.com/docs/reference/backend-api/tag/machine-tokens), it is subject to the [Backend API rate limits](/docs/rate-limits).
Expand Down Expand Up @@ -57,12 +55,20 @@ You can verify machine tokens in two ways:
1. Using Clerk's Backend SDKs (recommended)
2. Manually verifying the machine token JWT using your instance's public key.

### Examples Using Clerk's Backend SDKs
### Using Clerk's Backend SDKs

By default, authenticating requests, will default to authenticating user [session requests](/docs/session-requests/overview).

For machine requests, you can use the `entity: 'machine'` option to authenticate requests.

> [!WARNING]
> The `entity: 'machine'` option is only available in the Clerk Next.js SDK and Clerk Backend Javascript SDK during the beta.
<Tabs items={['Next.js Middleware', 'Next.js API Route', 'Node.js HTTP Server']}>
#### Examples

<Tabs items={['Next.js Middleware', 'Next.js API Route']}>
<Tab>
```tsx import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";

const isMachineRoute = createRouteMatcher(["/api/cron"]);

export default clerkMiddleware(async (auth, req) => {
Expand All @@ -85,54 +91,21 @@ You can verify machine tokens in two ways:
import { NextResponse } from 'next/server';
import { runCronJob } from './cronJob';

export const POST = async () => {
const { isMachineAuthenticated } = await auth({ entity: 'machine' });
export const POST = async () => {
const { isMachineAuthenticated } = await auth({ entity: 'machine' });

if (!isMachineAuthenticated) {
return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
}
if (!isMachineAuthenticated) {
return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
}

await runCronJob();
await runCronJob();

return NextResponse.json({ message: 'Cron job ran' });
};
return NextResponse.json({ message: 'Cron job ran' });
};
```
</Tab>

<Tab>
```tsx
import { createClerkClient } from '@clerk/backend';
import http from 'http';

const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY });

const server = http.createServer(async (req, res) => {
try {
const { isValid } = await clerk.authenticateRequest(req, {
entity: 'machine',
});

if (!isValid) {
res.writeHead(401);
res.end(JSON.stringify({ message: 'Unauthorized' }));
return;
}

await runCronJob();

res.writeHead(200);
res.end(JSON.stringify({ message: 'Success' }));
} catch (err) {
res.writeHead(500);
res.end(JSON.stringify({ message: 'Internal Server Error' }));
}
});

server.listen(3000, () => {
console.log('Server running on port 3000');
});
```
</Tab>
</Tabs>

### Manually verifying the machine token JWT

See the [manual JWT verification](/docs/machine-requests/manual-jwt) guide for more information.
8 changes: 6 additions & 2 deletions docs/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2728,12 +2728,16 @@
"items": [
[
{
"title": "Machine requests",
"href": "/docs/machine-requests/machine-requests"
"title": "Overview",
"href": "/docs/machine-requests/overview"
},
{
"title": "Machine tokens",
"href": "/docs/machine-requests/machine-tokens"
},
{
"title": "Manual JWT Verification",
"href": "/docs/machine-requests/manual-jwt"
}
]
]
Expand Down
34 changes: 31 additions & 3 deletions docs/references/backend/authenticate-request.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ It is recommended to set these options as [environment variables](/docs/deployme

---

- 'entity?'
- 'session' | 'machine'
- `entity?`
- `user` | `machine`

Determines what type of authentication to perform. If set to `'session'`, the function will authenticate a user session. If set to `'machine'`, the function will authenticate a machine-to-machine request. Defaults to `session`
Determines what type of authentication to perform. If set to `user`, the function will authenticate a user session. If set to `machine`, the function will authenticate a machine-to-machine request. Defaults to `user`

---

Expand Down Expand Up @@ -205,6 +205,34 @@ export async function GET(req: Request) {
}
```
### Machine-to-machine authentication
By default, `authenticateRequest()` will authenticate a [session request](/docs/session-requests/overview). To authenticate a machine-to-machine request, you need to set the `entity` option to `machine`.
Read more about [machine-to-machine authentication](/docs/machine-requests/overview).
```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 } = await clerkClient.authenticateRequest(req, {
entity: 'machine',
})

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

// Add logic to perform protected actions

return Response.json({ message: 'This is a machine-to-machine reply' })
}
```
### Networkless token verification
{/* Note: this example is duped from /authenticate-request. Probably a good opportunity to use a partial here */}
Expand Down
Loading

0 comments on commit c7a9659

Please sign in to comment.