Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove /nodejs/token-verification; update authenticateRequest() and verifyToken() reference docs #1242

Merged
merged 10 commits into from
Jul 16, 2024
8 changes: 6 additions & 2 deletions docs/backend-requests/handling/manual-jwt.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ For every request, you must validate its token to make sure it hasn't expired an

The `authenticateRequest()` method from Clerk's JavaScript Backend SDK does all of this for you. It accepts the request object and authenticates the session token in it. See the [reference page](/docs/references/backend/authenticate-request) for more information.

The following example uses the `authenticateRequest()` method to verify the token passed by the frontend, and performs a networkless authentication. This will verify if the user is signed into the application or not.
## Networkless token verification

{/* Note: this example is duped from /authenticate-request. Probably a good opportunity to use a partial here */}

The following example uses the `authenticateRequest()` method to verify the token passed by the frontend, and performs a networkless authentication by passing `secretKey` to `createClerkClient()`. This will verify if the user is signed into the application or not.
alexisintech marked this conversation as resolved.
Show resolved Hide resolved

```tsx
import { createClerkClient } from '@clerk/backend';
Expand All @@ -27,7 +31,7 @@ export async function GET(req: Request) {
return Response.json({ status: 401 });
}

// Perform protected actions
// Add logic to perform protected actions

return Response.json({ message: 'This is a reply' });
}
Expand Down
4 changes: 2 additions & 2 deletions docs/backend-requests/handling/nodejs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,8 @@ These options can be used with both [`ClerkExpressWithAuth`](#clerk-express-with
| Name | Type | Description |
| ----------- | ----------- | -------------- |
| `audience` | `string \| string[]` | A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). If passed, it is checked against the `aud` claim in the token. |
| `authorizedParties`| `string[]` | Can be used to validate that the `azp` claim equals any of your known origins that are permitted to generate those tokens. This is an extra security check that we highly recommend that you do. For more information, refer to [Manual JWT Verification](https://clerk.com/docs/backend-requests/handling/manual-jwt).<br />An example of the value you can pass is: `['http://localhost:4003', 'https://clerk.dev']` |
| `jwtKey` | `string` | Clerk's JWT session token can be verified in a networkless manner using the JWT verification key. By default, Clerk will use our well-known JWKs endpoint to fetch and cache the key for any subsequent token verification. If you use the [`CLERK_JWT_KEY` environment variable](/docs/deployments/clerk-environment-variables#api-and-sdk-configuration) or the `jwtKey` option to supply the key, Clerk will pick it up and do networkless verification for session tokens using it. For more information, refer to [Networkless Token Verification](/docs/references/nodejs/token-verification#validate-the-authorized-party-of-a-session-token). |
| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.<br/>For example: `['http://localhost:3000', 'https://example.com']` |
| `jwtKey` | `string` | Used to verify the session token in a networkless manner. Supply the PEM public key from the **[API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section of the Clerk Dashboard. **It's recommended to use [the environment variable](/docs/deployments/clerk-environment-variables) instead.** For more information, refer to [Manual JWT verification](/docs/backend-requests/handling/manual-jwt). |
| `onError` | `(error: ClerkAPIResponseError) => unknown` | This function can act as a custom error handler tailored to the needs of your application. |
| `signInUrl` | `string` | The URL to redirect to when the user is not authenticated. |
{/* | `strict` | `boolean` | When set to `true`, the middleware will raise an error when an unauthenticated request is made. When set to `false`, the middleware will return an empty auth object. | */}
Expand Down
4 changes: 2 additions & 2 deletions docs/deployments/clerk-environment-variables.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ The following environment variables enable you to configure API and SDK behavior
| `CLERK_JS_VERSION` | Sets the npm version for `@clerk/clerk-js`. |
| `CLERK_API_URL` | Sets the Clerk API URL for debugging. Defaults to `"https://api.clerk.com"` |
| `CLERK_API_VERSION` | Sets the version of the Clerk API to use. Defaults to `"v1"` |
| `CLERK_JWT_KEY` | Sets the JWT verification key that Clerk will use to provide networkless JWT session token verification. See [Networkless Token Verification](/docs/references/nodejs/token-verification#validate-the-authorized-party-of-a-session-token) to learn more. |
| `CLERK_JWT_KEY` | Sets the JWT verification key that Clerk will use to provide networkless JWT session token verification. Refer to [Manual JWT verification](/docs/backend-requests/handling/manual-jwt). |
| `CLERK_FAPI` | Sets the URL to your Clerk apps' Frontend API. |
| `CLERK_PROXY_URL` | Sets the URL for your proxy. |
</Tab>
Expand All @@ -92,7 +92,7 @@ The following environment variables enable you to configure API and SDK behavior
| `NEXT_PUBLIC_CLERK_FAPI` | Sets the URL to your Clerk app's Frontend API. |
| `NEXT_PUBLIC_CLERK_PROXY_URL` | Sets the URL for your proxy. |
| `CLERK_ENCRYPTION_KEY` | Sets the encryption key to securely propagate `clerkMiddleware` dynamic keys during request time. A 128-bit, pseudorandom value should be used. See [Dynamic keys](/docs/references/nextjs/clerk-middleware#dynamic-keys) to learn more. |
| `CLERK_JWT_KEY` | Sets the JWT verification key that Clerk will use to provide networkless JWT session token verification. See [Networkless Token Verification](/docs/references/nodejs/token-verification#validate-the-authorized-party-of-a-session-token) to learn more. |
| `CLERK_JWT_KEY` | Sets the JWT verification key that Clerk will use to provide networkless JWT session token verification. Refer to [Manual JWT verification](/docs/backend-requests/handling/manual-jwt). |
</Tab>

</Tabs>
Expand Down
59 changes: 44 additions & 15 deletions docs/references/backend/authenticate-request.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ description: Use Clerk's Backend SDK to verify a token passed from the frontend.

# `authenticateRequest()`

Authenticates a token passed from the frontend. Networkless if the `secretKey` or `jwtKey` are provided. Otherwise, performs a network call to retrieve the JWKS from [Clerk's Backend API](/docs/reference/backend-api/tag/JWKS#operation/GetJWKS).
Authenticates a token passed from the frontend. Networkless if the `jwtKey` is provided. Otherwise, performs a network call to retrieve the JWKS from [Clerk's Backend API](/docs/reference/backend-api/tag/JWKS#operation/GetJWKS).

```tsx
function authenticateRequest: (request: Request, options: AuthenticateRequestOptions) => Promise<RequestState>;
Expand All @@ -22,36 +22,63 @@ function authenticateRequest: (request: Request, options: AuthenticateRequestOpt

## `AuthenticateRequestOptions`

It is recommended to set these options as [environment variables](/docs/deployments/clerk-environment-variables#api-and-sdk-configuration) where possible, and then pass them to the function. For example, you can set the `secretKey` option using the `CLERK_SECRET_KEY` environment variable, and then pass it to the function like this: `createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should also mention the publishableKey here.

Copy link
Member Author

@alexisintech alexisintech Jul 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mention it throughout the doc - did you see the example sections?
It's not required when using it with a higher level SDK, but it is required if using it with the backend SDK on its own (using createClerkClient) which I explain and demonstrate in the example sections


> [!WARNING]
> You must provide either `jwtKey` or `secretKey`.

| Name | Type | Description |
| --- | --- | --- |
| `secretKey?` | `string` | The Clerk secret key from the [API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. |
| `secretKey?` | `string` | The Clerk secret key from the [API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. |
| `publishableKey?` | `string` | The Clerk publishable key from the [API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. |
| `jwtKey?` | `string` | Used to verify the session token in a networkless manner. Supply the PEM public key from the **[API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section of the Clerk Dashboard. For more information, refer to [Manual JWT verification](/docs/backend-requests/handling/manual-jwt). |
| `domain?` | `string` | The domain for the application. For development, you can pass the localhost your application is running on. For example: `localhost:3001` |
| `isSatellite?` | `boolean` | Set to `true` if the instance is a satellite domain in a multi-domain setup. |
| `proxyUrl?` | `string` | The proxy URL from a multi-domain setup. |
| `signInUrl?` | `string` | The sign-in URL from a multi-domain setup. It's recommended to use [the environment variable](/docs/deployments/clerk-environment-variables#sign-in-and-sign-up-redirects) instead. |
| `signUpUrl?` | `string` | It's recommended to use sign-up URL from a multi-domain setup. Use [the environment variable](/docs/deployments/clerk-environment-variables#sign-in-and-sign-up-redirects) instead. |
| `signInForceRedirectUrl?` | `string` | If provided, this URL will always be redirected to after the user signs in. It's recommended to use [the environment variable](/docs/deployments/clerk-environment-variables#sign-in-and-sign-up-redirects) instead. |
| `signUpForceRedirectUrl?` | `string` | If provided, this URL will always be redirected to after the user signs up. It's recommended to use [the environment variable](/docs/deployments/clerk-environment-variables#sign-in-and-sign-up-redirects) instead. |
| `signInFallbackRedirectUrl?` | `string` | The fallback URL to redirect to after the user signs in, if there's no `redirect_url` in the path already. Defaults to `/`. It's recommended to use [the environment variable](/docs/deployments/clerk-environment-variables#sign-in-and-sign-up-redirects) instead. |
| `signUpFallbackRedirectUrl?` | `string` | The fallback URL to redirect to after the user signs up, if there's no `redirect_url` in the path already. Defaults to `/`. It's recommended to use [the environment variable](/docs/deployments/clerk-environment-variables#sign-in-and-sign-up-redirects) instead. |
| `jwtKey?` | `string` | The PEM public key from the **[API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section of the Clerk Dashboard. It's recommended to use [the environment variable](/docs/deployments/clerk-environment-variables) instead. |
| `signInUrl?` | `string` | The sign-in URL from a multi-domain setup. |
| `signUpUrl?` | `string` | It's recommended to use sign-up URL from a multi-domain setup. |
| `afterSignInUrl?` | `string` | Full URL or path to navigate to after successful sign in. Defaults to `/`. |
| `afterSignUpUrl?` | `string` | Full URL or path to navigate to after successful sign up. Defaults to `/`. |
| `audience?` | `string \| string[]` | A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). |
| `authorizedParties`| `string[]` | | A list of authorized parties. For example, `['http://localhost:4003', 'https://clerk.com']` |
| `clockSkewInMs?` | `number` | Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token. Defaults to 5000 ms (5 seconds).|
| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.<br/>For example: `['http://localhost:3000', 'https://example.com']` |
| `clockSkewInMs?` | `number` | Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token. Defaults to 5000 ms (5 seconds). |
| `jwksCacheTtlInMs?` (deprecated) | `number` | Deprecated. Specifying a cache TTL is now a no-op. |
| `skipJwksCache?` | `boolean` | A flag to skip ignore cache and always fetch JWKS before each jwt verification.|
| `skipJwksCache?` | `boolean` | A flag to skip ignore cache and always fetch JWKS before each jwt verification. |

## Examples

### With a higher-level SDK

`authenticateRequest()` requires `publishableKey` to be set. If you are importing `clerkClient` from a higher-level SDK, such as Next.js, then `clerkClient` infers the `publishableKey` from your [environment variables](/docs/deployments/clerk-environment-variables#clerk-publishable-and-secret-keys).

```tsx
import { clerkClient } from '@clerk/nextjs/server';

export async function GET(req: Request) {
const { isSignedIn } = await clerkClient.authenticateRequest(req);

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

## Example
// Perform protected actions
// Add logic to perform protected actions

The following example takes the token passed by the frontend as a Bearer token in the Authorization header, and performs a networkless authenication by passing `secretKey` to `createClerkClient()`. This will verify if the user is signed into the application or not.
return Response.json({ message: 'This is a reply' });
}
```

### With the Backend SDK on its own

If you are using the [JavaScript Backend SDK](/docs/references/backend/overview) on its own, you need to provide the `secretKey` and `publishableKey` to `createClerkClient()` so that it is passed to `authenticateRequest()`. You can set these values as [environment variables](/docs/deployments/clerk-environment-variables#clerk-publishable-and-secret-keys) and then pass them to the function.

```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 { isSignedIn } = await clerkClient.authenticateRequest(req);
Expand All @@ -60,8 +87,10 @@ export async function GET(req: Request) {
return Response.json({ status: 401 });
}

// Perform protected actions
// Add logic to perform protected actions

return Response.json({ message: 'This is a reply' });
}
```

### Networkless token verification
Loading
Loading