From ae27b59125ea36e734ff41f7c4256a2e7a21475f Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Mon, 8 Jul 2024 16:16:40 -0400
Subject: [PATCH 01/10] Remove /nodejs/token-verification
---
docs/backend-requests/handling/manual-jwt.mdx | 8 ++-
.../backend/authenticate-request.mdx | 4 +-
docs/references/nodejs/token-verification.mdx | 57 -------------------
3 files changed, 8 insertions(+), 61 deletions(-)
delete mode 100644 docs/references/nodejs/token-verification.mdx
diff --git a/docs/backend-requests/handling/manual-jwt.mdx b/docs/backend-requests/handling/manual-jwt.mdx
index 1bbd8cfe43..122dce2ae5 100644
--- a/docs/backend-requests/handling/manual-jwt.mdx
+++ b/docs/backend-requests/handling/manual-jwt.mdx
@@ -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.
```tsx
import { createClerkClient } from '@clerk/backend';
@@ -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' });
}
diff --git a/docs/references/backend/authenticate-request.mdx b/docs/references/backend/authenticate-request.mdx
index 58a53ff567..5d97a9d0f0 100644
--- a/docs/references/backend/authenticate-request.mdx
+++ b/docs/references/backend/authenticate-request.mdx
@@ -44,7 +44,7 @@ function authenticateRequest: (request: Request, options: AuthenticateRequestOpt
## Example
-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.
+The following example takes the token passed by the frontend as a Bearer token in the Authorization header, and performs a networkless authentication by passing `secretKey` to `createClerkClient()`. This will verify if the user is signed into the application or not.
```tsx
import { createClerkClient } from '@clerk/backend';
@@ -60,7 +60,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' });
}
diff --git a/docs/references/nodejs/token-verification.mdx b/docs/references/nodejs/token-verification.mdx
deleted file mode 100644
index c6b50dcb83..0000000000
--- a/docs/references/nodejs/token-verification.mdx
+++ /dev/null
@@ -1,57 +0,0 @@
----
-title: Networkless token verification | Clerk Node.js SDK
-description: Clerk's JWT session token can be verified in a networkless manner using the JWT verification key.
----
-
-# Networkless token verification
-
-Clerk's JWT session token can be verified in a networkless manner using the JWT verification key. By default, Clerk will use our JWKs endpoint to fetch and cache the key for any subsequent verification. If you use the `CLERK_JWT_KEY` environment variable to supply the key, Clerk will pick it up and do networkless verification for session tokens using it.
-
-To learn more about Clerk's token verification, you can find more information on our guide to [validating session tokens](/docs/backend-requests/handling/manual-jwt).
-
-The value of the JWT verification key can also be added on the instance level or on any single middleware call e.g. for Next.js.
-
-```js
-import { withAuth } from '@clerk/nextjs';
-
-const handler = (req, res) => {
- // ...
-};
-
-withAuth(handler, { jwtKey: 'my_clerk_public_key' });
-```
-
-Custom instance initialization:
-
-```js
-import { createClerkClient } from '@clerk/clerk-sdk-node';
-
-const clerk = createClerkClient({ jwtKey: 'my_clerk_public_key' });
-```
-
-## Validate the authorized party of a session token
-
-Clerk's JWT session token contains the `azp` claim, which equals the Origin of the request during token generation. You can provide the middlewares with a list of allowlisted origins to verify against, to protect your application of the subdomain cookie leaking attack. You can find an example below:
-
-
-```js
-import { requireAuth } from '@clerk/nextjs';
-
-const authorizedParties = ['http://localhost:3000', 'https://example.com']
-
-function handler(req: RequireAuthProp, res: NextApiResponse) {
- // do something with the auth attribute
-}
-
-export requireAuth(handler, { authorizedParties });
-```
-
-```js
-// Node + Express app
-import { ClerkExpressRequireAuth } from '@clerk/clerk-sdk-node';
-
-const authorizedParties = ['http://localhost:3000', 'https://example.com'];
-
-app.use(ClerkExpressRequireAuth({ authorizedParties }));
-```
-
\ No newline at end of file
From 369a58b271ff47d11d6c81a4af8fa4617da96b00 Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Mon, 8 Jul 2024 16:31:20 -0400
Subject: [PATCH 02/10] fix broken links (mostly update prop description)
---
docs/backend-requests/handling/nodejs.mdx | 2 +-
docs/deployments/clerk-environment-variables.mdx | 4 ++--
docs/references/backend/authenticate-request.mdx | 4 ++--
docs/references/backend/verify-token.mdx | 2 +-
docs/references/gatsby/with-server-auth.mdx | 4 ++--
docs/references/nextjs/auth-middleware.mdx | 2 +-
docs/references/nextjs/clerk-middleware.mdx | 2 +-
7 files changed, 10 insertions(+), 10 deletions(-)
diff --git a/docs/backend-requests/handling/nodejs.mdx b/docs/backend-requests/handling/nodejs.mdx
index 500b0cdad6..a1444b3ddc 100644
--- a/docs/backend-requests/handling/nodejs.mdx
+++ b/docs/backend-requests/handling/nodejs.mdx
@@ -174,7 +174,7 @@ These options can be used with both [`ClerkExpressWithAuth`](#clerk-express-with
| ----------- | ----------- | -------------- |
| `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).
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). |
+| `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. | */}
diff --git a/docs/deployments/clerk-environment-variables.mdx b/docs/deployments/clerk-environment-variables.mdx
index 5d35f203df..4971189579 100644
--- a/docs/deployments/clerk-environment-variables.mdx
+++ b/docs/deployments/clerk-environment-variables.mdx
@@ -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. |
@@ -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). |
diff --git a/docs/references/backend/authenticate-request.mdx b/docs/references/backend/authenticate-request.mdx
index 5d97a9d0f0..ebd4fb88fe 100644
--- a/docs/references/backend/authenticate-request.mdx
+++ b/docs/references/backend/authenticate-request.mdx
@@ -24,7 +24,7 @@ function authenticateRequest: (request: Request, options: AuthenticateRequestOpt
| 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` | Used to verify the session token in a networkless manner. Supply 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. |
| `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. |
@@ -35,7 +35,7 @@ function authenticateRequest: (request: Request, options: AuthenticateRequestOpt
| `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. |
+| `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). |
| `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).|
diff --git a/docs/references/backend/verify-token.mdx b/docs/references/backend/verify-token.mdx
index 9ca0276350..248bba223c 100644
--- a/docs/references/backend/verify-token.mdx
+++ b/docs/references/backend/verify-token.mdx
@@ -33,7 +33,7 @@ function verifyToken: (token: string, options: VerifyTokenOptions) => Promise 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. |
+| `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). |
| `secretKey?` | `string` | The Clerk secret key from the [API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. |
| `skipJwksCache?` | `boolean` | A flag to ignore the JWKS cache and always fetch JWKS before each JWT verification. |
| `apiUrl?` | `string` | The Clerk [Backend API](/docs/reference/backend-api) endpoint. Defaults to `'https://api.clerk.com'`. |
diff --git a/docs/references/gatsby/with-server-auth.mdx b/docs/references/gatsby/with-server-auth.mdx
index 9451467cf5..af0713e6dc 100644
--- a/docs/references/gatsby/with-server-auth.mdx
+++ b/docs/references/gatsby/with-server-auth.mdx
@@ -74,5 +74,5 @@ Gatsby then automatically passes the result of `withServer`'s callback to the `s
| `loadUser?` | `boolean` | If `true`, load the user data for the current auth session. |
| `loadSession?` | `boolean` | If `true`, load the session data for the current auth session. |
| `loadOrg?` | `boolean` | If `true`, load the organization data for the current auth session. |
-| `jwtKey?` | `string` | An optional [custom JWT key](/docs/references/nodejs/token-verification#networkless-token-verification-using-the-jwt-verification-key) to use for session token validation. |
-| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
For example:
`['http://localhost:3000', 'https://example.com']`
For more information, refer to the [reference guide](/docs/references/nodejs/token-verification#validate-the-authorized-party-of-a-session-token). |
\ No newline at end of file
+| `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). |
+| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
For example:
`['http://localhost:3000', 'https://example.com']`
For more information, refer to the [reference guide](/docs/references/nodejs/token-verification#validate-the-authorized-party-of-a-session-token). |
diff --git a/docs/references/nextjs/auth-middleware.mdx b/docs/references/nextjs/auth-middleware.mdx
index 8ea06d800f..f3f2ee0945 100644
--- a/docs/references/nextjs/auth-middleware.mdx
+++ b/docs/references/nextjs/auth-middleware.mdx
@@ -262,7 +262,7 @@ The `authMiddleware()` method accepts an optional object. The following options
| `isSatellite?` | `boolean` | When using Clerk's satellite feature, this should be enabled for secondary domains. |
| `proxyUrl?` | `string` | If using a proxy, specify the URL of the proxy. |
| `jwksCacheTtlInMs?` | `number` | Set the JWKs cache TTL, in milliseconds. |
-| `jwtKey?` | `string` | An optional [custom JWT key](/docs/references/nodejs/token-verification#networkless-token-verification-using-the-jwt-verification-key) to use for session token validation. |
+| `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). |
| `ignoredRoutes?` | `string[]` | A list of routes that should be ignored by the middleware. This list typically includes routes for static files or Next.js internals. For improved performance, these routes should be skipped using the default config.matcher instead. |
| `publicRoutes?` | `string[]` | A list of routes that should be accessible without authentication. You can use glob patterns to match multiple routes or a function to match against the request object. For example: `['/foo', '/bar(.*)']` or `[/^\/foo\/.*$/]`
The sign in and sign up URLs are included by default, unless a function is provided. |
| `publishableKey?` | `string` | An alternate Clerk publishable key. |
diff --git a/docs/references/nextjs/clerk-middleware.mdx b/docs/references/nextjs/clerk-middleware.mdx
index 3902c73e8a..654cef2a0f 100644
--- a/docs/references/nextjs/clerk-middleware.mdx
+++ b/docs/references/nextjs/clerk-middleware.mdx
@@ -290,7 +290,7 @@ The `clerkMiddleware()` function accepts an optional object. The following optio
| `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). |
| `domain?` | `string` | The domain used for satellites to inform Clerk where this application is deployed. |
| `isSatellite?` | `boolean` | When using Clerk's satellite feature, this should be set to `true` for secondary domains. |
-| `jwtKey?` | `string` | An optional [custom JWT key](/docs/references/nodejs/token-verification#networkless-token-verification-using-the-jwt-verification-key) to use for session token validation. |
+| `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). |
| `proxyUrl?` | `string` | Specify the URL of the proxy, if using a proxy. |
| `signInUrl?` | `string` | An alternative sign in URL. |
| `signUpUrl?` | `string` | An alternative sign up URL. |
From 87adeca2240b115dbd4e7ea86e4f6cc6a7369bbc Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Mon, 8 Jul 2024 16:44:55 -0400
Subject: [PATCH 03/10] fix broken links (update authorizedParties prop)
---
docs/backend-requests/handling/nodejs.mdx | 2 +-
docs/references/backend/authenticate-request.mdx | 2 +-
docs/references/backend/verify-token.mdx | 2 +-
docs/references/gatsby/with-server-auth.mdx | 2 +-
docs/references/nextjs/auth-middleware.mdx | 2 +-
docs/references/nextjs/clerk-middleware.mdx | 2 +-
6 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/docs/backend-requests/handling/nodejs.mdx b/docs/backend-requests/handling/nodejs.mdx
index a1444b3ddc..a852c38790 100644
--- a/docs/backend-requests/handling/nodejs.mdx
+++ b/docs/backend-requests/handling/nodejs.mdx
@@ -173,7 +173,7 @@ 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).
An example of the value you can pass is: `['http://localhost:4003', 'https://clerk.dev']` |
+| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
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. |
diff --git a/docs/references/backend/authenticate-request.mdx b/docs/references/backend/authenticate-request.mdx
index ebd4fb88fe..6760bb0906 100644
--- a/docs/references/backend/authenticate-request.mdx
+++ b/docs/references/backend/authenticate-request.mdx
@@ -37,7 +37,7 @@ function authenticateRequest: (request: Request, options: AuthenticateRequestOpt
| `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` | 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). |
| `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']` |
+| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
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.|
diff --git a/docs/references/backend/verify-token.mdx b/docs/references/backend/verify-token.mdx
index 248bba223c..fea73bbc51 100644
--- a/docs/references/backend/verify-token.mdx
+++ b/docs/references/backend/verify-token.mdx
@@ -31,7 +31,7 @@ function verifyToken: (token: string, options: VerifyTokenOptions) => Promise 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). |
| `secretKey?` | `string` | The Clerk secret key from the [API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. |
diff --git a/docs/references/gatsby/with-server-auth.mdx b/docs/references/gatsby/with-server-auth.mdx
index af0713e6dc..5a900c85b8 100644
--- a/docs/references/gatsby/with-server-auth.mdx
+++ b/docs/references/gatsby/with-server-auth.mdx
@@ -75,4 +75,4 @@ Gatsby then automatically passes the result of `withServer`'s callback to the `s
| `loadSession?` | `boolean` | If `true`, load the session data for the current auth session. |
| `loadOrg?` | `boolean` | If `true`, load the organization data for the current auth session. |
| `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). |
-| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
For example:
`['http://localhost:3000', 'https://example.com']`
For more information, refer to the [reference guide](/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.
For example: `['http://localhost:3000', 'https://example.com']` |
diff --git a/docs/references/nextjs/auth-middleware.mdx b/docs/references/nextjs/auth-middleware.mdx
index f3f2ee0945..0a484e6e91 100644
--- a/docs/references/nextjs/auth-middleware.mdx
+++ b/docs/references/nextjs/auth-middleware.mdx
@@ -253,7 +253,7 @@ The `authMiddleware()` method accepts an optional object. The following options
| `afterAuth?` | `function` | Called after the authentication middleware is executed. This function has access to the [`Auth`](/docs/references/nextjs/auth-object) object and can be used to execute logic based on the auth state. |
| `apiRoutes?` | `string[]` | A list of routes that should return 401 if the user is not signed in. You can use glob patterns to match multiple routes or a function to match against the request object. For example: `['/foo', '/bar(.*)']` or `[/^\/foo\/.*$/]` |
| `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[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
For example:
`['http://localhost:3000', 'https://example.com']`
For more information, refer to the [reference guide](/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.
For example: `['http://localhost:3000', 'https://example.com']` |
| `beforeAuth?` | `function` | A function called before the authentication middleware is executed. If a redirect response is returned, the middleware will respect it and redirect the user. If `false` is returned, the auth middleware will not execute and the request will be handled as if the auth middleware was not present. |
| `clockSkewInSeconds? (deprecated)` | `number` | Deprecated in favor of `clockSkewInMs`. |
| `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). |
diff --git a/docs/references/nextjs/clerk-middleware.mdx b/docs/references/nextjs/clerk-middleware.mdx
index 654cef2a0f..465edf1654 100644
--- a/docs/references/nextjs/clerk-middleware.mdx
+++ b/docs/references/nextjs/clerk-middleware.mdx
@@ -286,7 +286,7 @@ The `clerkMiddleware()` function accepts an optional object. The following optio
| 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[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
For example: `['http://localhost:3000', 'https://example.com']`
For more information, refer to the [reference guide](/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.
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). |
| `domain?` | `string` | The domain used for satellites to inform Clerk where this application is deployed. |
| `isSatellite?` | `boolean` | When using Clerk's satellite feature, this should be set to `true` for secondary domains. |
From dc9c88c2c481a06699194e8d9342216e0c904ab8 Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Wed, 10 Jul 2024 14:29:33 -0400
Subject: [PATCH 04/10] recommend env vars
---
.../backend/authenticate-request.mdx | 25 +++++++++++--------
1 file changed, 15 insertions(+), 10 deletions(-)
diff --git a/docs/references/backend/authenticate-request.mdx b/docs/references/backend/authenticate-request.mdx
index 6760bb0906..c945678c01 100644
--- a/docs/references/backend/authenticate-request.mdx
+++ b/docs/references/backend/authenticate-request.mdx
@@ -22,25 +22,30 @@ 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 })`.
+
+> [!WARNING]
+> You must provide either `jwtKey` or `secretKey`.
+
| Name | Type | Description |
| --- | --- | --- |
-| `secretKey?` | `string` | Used to verify the session token in a networkless manner. Supply the Clerk secret key from the [API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. |
+| `secretKey?` | `string` | Used to verify the session token in a networkless manner. Supply 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. |
| `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` | 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). |
+| `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. |
+| `signInForceRedirectUrl?` | `string` | If provided, this URL will always be redirected to after the user signs in. |
+| `signUpForceRedirectUrl?` | `string` | If provided, this URL will always be redirected to after the user signs up. |
+| `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 `/`. |
+| `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 `/`. |
+| `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). |
| `audience?` | `string \| string[]` | A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). |
| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
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).|
+| `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. |
## Example
From f40d06c7fb68ee2bbf889c5d95fa1a3fff199d42 Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Wed, 10 Jul 2024 15:18:44 -0400
Subject: [PATCH 05/10] add examples for using backend sdk on its own vs with
sdk; update options table
---
.../backend/authenticate-request.mdx | 39 ++++++++++++++-----
1 file changed, 30 insertions(+), 9 deletions(-)
diff --git a/docs/references/backend/authenticate-request.mdx b/docs/references/backend/authenticate-request.mdx
index c945678c01..3c41bccf69 100644
--- a/docs/references/backend/authenticate-request.mdx
+++ b/docs/references/backend/authenticate-request.mdx
@@ -24,9 +24,6 @@ function authenticateRequest: (request: Request, options: AuthenticateRequestOpt
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 })`.
-> [!WARNING]
-> You must provide either `jwtKey` or `secretKey`.
-
| Name | Type | Description |
| --- | --- | --- |
| `secretKey?` | `string` | Used to verify the session token in a networkless manner. Supply the Clerk secret key from the [API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. |
@@ -36,10 +33,8 @@ It is recommended to set these options as [environment variables](/docs/deployme
| `proxyUrl?` | `string` | The proxy URL from a multi-domain setup. |
| `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. |
-| `signInForceRedirectUrl?` | `string` | If provided, this URL will always be redirected to after the user signs in. |
-| `signUpForceRedirectUrl?` | `string` | If provided, this URL will always be redirected to after the user signs up. |
-| `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 `/`. |
-| `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 `/`. |
+| `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 `/`. |
| `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). |
| `audience?` | `string \| string[]` | A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). |
| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
For example: `['http://localhost:3000', 'https://example.com']` |
@@ -47,9 +42,32 @@ It is recommended to set these options as [environment variables](/docs/deployme
| `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. |
-## Example
+## 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 });
+ }
+
+ // Perform protected actions
+ // Add logic to perform protected actions
+
+ return Response.json({ message: 'This is a reply' });
+}
+```
-The following example takes the token passed by the frontend as a Bearer token in the Authorization header, and performs a networkless authentication by passing `secretKey` to `createClerkClient()`. This will verify if the user is signed into the application or not.
+### 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';
@@ -57,6 +75,7 @@ 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);
@@ -70,3 +89,5 @@ export async function GET(req: Request) {
return Response.json({ message: 'This is a reply' });
}
```
+
+### Networkless token verification
From 6d19f04f1f4ac85814e37759e8492ae871cdd5d2 Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Wed, 10 Jul 2024 15:39:56 -0400
Subject: [PATCH 06/10] update verifytoken example
---
docs/references/backend/verify-token.mdx | 78 ++++++++++++------------
1 file changed, 38 insertions(+), 40 deletions(-)
diff --git a/docs/references/backend/verify-token.mdx b/docs/references/backend/verify-token.mdx
index fea73bbc51..bb44e8230e 100644
--- a/docs/references/backend/verify-token.mdx
+++ b/docs/references/backend/verify-token.mdx
@@ -10,7 +10,7 @@ description: Use Clerk's Backend SDK to verify a token signature.
# `verifyToken()`
-Verifies a Clerk-generated token signature.
+Verifies a Clerk-generated token signature. 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).
```js
function verifyToken: (token: string, options: VerifyTokenOptions) => Promise>;
@@ -25,6 +25,8 @@ function verifyToken: (token: string, options: VerifyTokenOptions) => Promise [!WARNING]
> You must provide either `jwtKey` or `secretKey`.
@@ -33,7 +35,7 @@ function verifyToken: (token: string, options: VerifyTokenOptions) => Promise 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). |
+| `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). |
| `secretKey?` | `string` | The Clerk secret key from the [API Keys](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. |
| `skipJwksCache?` | `boolean` | A flag to ignore the JWKS cache and always fetch JWKS before each JWT verification. |
| `apiUrl?` | `string` | The Clerk [Backend API](/docs/reference/backend-api) endpoint. Defaults to `'https://api.clerk.com'`. |
@@ -41,58 +43,54 @@ function verifyToken: (token: string, options: VerifyTokenOptions) => Promise
-
- ```ts title="app/api/verify-token/route.ts"
- import { verifyToken } from '@clerk/backend';
- import { cookies } from 'next/headers';
+```ts
+import { verifyToken } from '@clerk/backend';
+import { cookies } from 'next/headers';
+
+export async function GET(request: Request) {
+ const cookieStore = cookies()
+ const sessToken = cookieStore.get('__session')?.value
+ const bearerToken = request.headers.get('Authorization')?.replace('Bearer ', '');
+ const token = sessToken || bearerToken;
+
+ if (!token) {
+ return Response.json({ error: 'Token not found. User must sign in.' }, { status: 401 });
+ }
- export async function GET(request: Request) {
- const cookieStore = cookies()
- const sessToken = cookieStore.get('__session')?.value
- const bearerToken = request.headers.get('Authorization')?.replace('Bearer ', '');
- const token = sessToken || bearerToken;
+ try {
+ const verifiedToken = await verifyToken(token, {
+ jwtKey: process.env.CLERK_JWT_KEY,
+ });
- if (!token) {
- return Response.json({ error: 'Token not found. User must sign in.' }, { status: 401 });
+ // Check if the token is expired or not yet valid
+ const currentTime = Math.floor(Date.now() / 1000);
+ if (verifiedToken.exp < currentTime || verifiedToken.nbf > currentTime) {
+ throw new Error("Token is expired or not yet valid");
}
- try {
- const verifiedToken = await verifyToken(token, {
- jwtKey: process.env.CLERK_JWT_KEY,
- });
-
- // Check if the token is expired or not yet valid
- const currentTime = Math.floor(Date.now() / 1000);
- if (verifiedToken.exp < currentTime || verifiedToken.nbf > currentTime) {
- throw new Error("Token is expired or not yet valid");
- }
-
- // Check if the token is issued by a permitted origin
- const permittedOrigins = ["http://localhost:3000", "https://example.com"]; // Replace with your permitted origins
- if (verifiedToken.azp && !permittedOrigins.includes(verifiedToken.azp)) {
- throw new Error("Invalid 'azp' claim");
- }
-
- return Response.json({ verifiedToken });
- } catch (error) {
- return Response.json({ error: 'Token not verified.' }, { status: 401 });
+ // Check if the token is issued by a permitted origin
+ const permittedOrigins = ["http://localhost:3000", "https://example.com"]; // Replace with your permitted origins
+ if (verifiedToken.azp && !permittedOrigins.includes(verifiedToken.azp)) {
+ throw new Error("Invalid 'azp' claim");
}
+
+ return Response.json({ verifiedToken });
+ } catch (error) {
+ return Response.json({ error: 'Token not verified.' }, { status: 401 });
}
- ```
-
-
+}
+```
If the token is valid, the response will contain a JSON object that looks something like this:
From c98b97d60b09137ace9b26614eb5d2075aa4ccc5 Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Wed, 10 Jul 2024 15:40:26 -0400
Subject: [PATCH 07/10] only jwtKey performs networkless token verification
---
docs/references/backend/authenticate-request.mdx | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)
diff --git a/docs/references/backend/authenticate-request.mdx b/docs/references/backend/authenticate-request.mdx
index 3c41bccf69..d98c44f63a 100644
--- a/docs/references/backend/authenticate-request.mdx
+++ b/docs/references/backend/authenticate-request.mdx
@@ -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;
@@ -24,10 +24,14 @@ function authenticateRequest: (request: Request, options: AuthenticateRequestOpt
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 })`.
+> [!WARNING]
+> You must provide either `jwtKey` or `secretKey`.
+
| Name | Type | Description |
| --- | --- | --- |
-| `secretKey?` | `string` | Used to verify the session token in a networkless manner. Supply 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. |
@@ -35,7 +39,6 @@ It is recommended to set these options as [environment variables](/docs/deployme
| `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 `/`. |
-| `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). |
| `audience?` | `string \| string[]` | A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). |
| `authorizedParties?` | `string[]` | An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
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). |
From 39c42f93546b85343f39c701fd9b0d4b340da2d5 Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Fri, 12 Jul 2024 12:51:05 -0400
Subject: [PATCH 08/10] update verifytoken example
---
docs/references/backend/verify-token.mdx | 31 +++++++++---------------
1 file changed, 12 insertions(+), 19 deletions(-)
diff --git a/docs/references/backend/verify-token.mdx b/docs/references/backend/verify-token.mdx
index bb44e8230e..9e6a87bc39 100644
--- a/docs/references/backend/verify-token.mdx
+++ b/docs/references/backend/verify-token.mdx
@@ -49,9 +49,8 @@ In the following example:
1. The PEM public key from the Clerk Dashboard is set in the environment variable `CLERK_JWT_KEY`.
1. The session token is retrieved from the `__session` cookie or the Authorization header.
-1. The token is verified in a networkless manner by passing the `jwtKey` to the `verifyToken()` method.
-1. The token's `exp` and `nbf` claims are checked.
-1. The token's `azp` claim is checked against the permitted origins. Verifying the `azp` claim on the server side ensures that the session token is generated from the expected frontend application. For example, if you are permitting tokens retrieved from http://localhost:3000, then the `azp` claim should equal http://localhost:3000.
+1. The token is verified in a networkless manner by passing the `jwtKey` prop.
+1. The `authorizedParties` prop is passed to verify that the session token is generated from the expected frontend application.
1. If the token is valid, the response contains the verified token.
```ts
@@ -59,32 +58,26 @@ import { verifyToken } from '@clerk/backend';
import { cookies } from 'next/headers';
export async function GET(request: Request) {
- const cookieStore = cookies()
- const sessToken = cookieStore.get('__session')?.value
- const bearerToken = request.headers.get('Authorization')?.replace('Bearer ', '');
+ const cookieStore = cookies();
+ const sessToken = cookieStore.get('__session')?.value;
+ const bearerToken = request.headers
+ .get('Authorization')
+ ?.replace('Bearer ', '');
const token = sessToken || bearerToken;
if (!token) {
- return Response.json({ error: 'Token not found. User must sign in.' }, { status: 401 });
+ return Response.json(
+ { error: 'Token not found. User must sign in.' },
+ { status: 401 }
+ );
}
try {
const verifiedToken = await verifyToken(token, {
jwtKey: process.env.CLERK_JWT_KEY,
+ authorizedParties: ['http://localhost:3001', 'api.example.com'], // Replace with your authorized parties
});
- // Check if the token is expired or not yet valid
- const currentTime = Math.floor(Date.now() / 1000);
- if (verifiedToken.exp < currentTime || verifiedToken.nbf > currentTime) {
- throw new Error("Token is expired or not yet valid");
- }
-
- // Check if the token is issued by a permitted origin
- const permittedOrigins = ["http://localhost:3000", "https://example.com"]; // Replace with your permitted origins
- if (verifiedToken.azp && !permittedOrigins.includes(verifiedToken.azp)) {
- throw new Error("Invalid 'azp' claim");
- }
-
return Response.json({ verifiedToken });
} catch (error) {
return Response.json({ error: 'Token not verified.' }, { status: 401 });
From 774197cc39e8fefba50fb4d7ee85f5d7b2842990 Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Fri, 12 Jul 2024 13:00:28 -0400
Subject: [PATCH 09/10] pass publishablekey to manual-jwt example
---
docs/backend-requests/handling/manual-jwt.mdx | 3 ++-
docs/references/backend/authenticate-request.mdx | 2 ++
2 files changed, 4 insertions(+), 1 deletion(-)
diff --git a/docs/backend-requests/handling/manual-jwt.mdx b/docs/backend-requests/handling/manual-jwt.mdx
index 122dce2ae5..a0cb811d8d 100644
--- a/docs/backend-requests/handling/manual-jwt.mdx
+++ b/docs/backend-requests/handling/manual-jwt.mdx
@@ -15,7 +15,7 @@ The `authenticateRequest()` method from Clerk's JavaScript Backend SDK does all
{/* 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.
+The following example uses the `authenticateRequest()` method with the [JavaScript Backend SDK](/docs/references/backend/overview) to verify the token passed by the frontend. This will verify if the user is signed into the application or not. For more information, like using the method with higher-level SDK's or performing networkless token verification, see the [`authenticateRequest()` reference](/docs/references/backend/authenticate-request).
```tsx
import { createClerkClient } from '@clerk/backend';
@@ -23,6 +23,7 @@ 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);
diff --git a/docs/references/backend/authenticate-request.mdx b/docs/references/backend/authenticate-request.mdx
index d98c44f63a..ca6c428d07 100644
--- a/docs/references/backend/authenticate-request.mdx
+++ b/docs/references/backend/authenticate-request.mdx
@@ -70,6 +70,8 @@ export async function GET(req: Request) {
### With the Backend SDK on its own
+{/* Note: this example is duped in /manual-jwt. Probably a good opportunity to use a partial here */}
+
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
From e7cc83f6a557e12a13a4ba9527eb05cdf8b1b5f9 Mon Sep 17 00:00:00 2001
From: Alexis Aguilar <98043211+alexisintech@users.noreply.github.com>
Date: Fri, 12 Jul 2024 16:35:47 -0400
Subject: [PATCH 10/10] update networkless verification examples
---
docs/backend-requests/handling/manual-jwt.mdx | 6 ++--
.../backend/authenticate-request.mdx | 29 +++++++++++++++++--
2 files changed, 31 insertions(+), 4 deletions(-)
diff --git a/docs/backend-requests/handling/manual-jwt.mdx b/docs/backend-requests/handling/manual-jwt.mdx
index a0cb811d8d..a52ec5948a 100644
--- a/docs/backend-requests/handling/manual-jwt.mdx
+++ b/docs/backend-requests/handling/manual-jwt.mdx
@@ -15,7 +15,7 @@ The `authenticateRequest()` method from Clerk's JavaScript Backend SDK does all
{/* Note: this example is duped from /authenticate-request. Probably a good opportunity to use a partial here */}
-The following example uses the `authenticateRequest()` method with the [JavaScript Backend SDK](/docs/references/backend/overview) to verify the token passed by the frontend. This will verify if the user is signed into the application or not. For more information, like using the method with higher-level SDK's or performing networkless token verification, see the [`authenticateRequest()` reference](/docs/references/backend/authenticate-request).
+The following example uses the `authenticateRequest()` method with the [JavaScript Backend SDK](/docs/references/backend/overview) to verify the token passed by the frontend, and performs a networkless authentication by passing `jwtKey`. This will verify if the user is signed into the application or not. For more information, like using the method with higher-level SDK's, see the [`authenticateRequest()` reference](/docs/references/backend/authenticate-request).
```tsx
import { createClerkClient } from '@clerk/backend';
@@ -26,7 +26,9 @@ export async function GET(req: Request) {
publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
});
- const { isSignedIn } = await clerkClient.authenticateRequest(req);
+ const { isSignedIn } = await clerkClient.authenticateRequest(req, {
+ jwtKey: process.env.CLERK_JWT_KEY,
+ });
if (!isSignedIn) {
return Response.json({ status: 401 });
diff --git a/docs/references/backend/authenticate-request.mdx b/docs/references/backend/authenticate-request.mdx
index ca6c428d07..faf5671a8c 100644
--- a/docs/references/backend/authenticate-request.mdx
+++ b/docs/references/backend/authenticate-request.mdx
@@ -70,8 +70,6 @@ export async function GET(req: Request) {
### With the Backend SDK on its own
-{/* Note: this example is duped in /manual-jwt. Probably a good opportunity to use a partial here */}
-
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
@@ -96,3 +94,30 @@ export async function GET(req: Request) {
```
### 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 with the [JavaScript Backend SDK](/docs/references/backend/overview) to verify the token passed by the frontend, and performs a networkless authentication by passing `jwtKey`. This will verify if the user is signed into the application or not.
+
+```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, {
+ jwtKey: process.env.CLERK_JWT_KEY,
+ });
+
+ if (!isSignedIn) {
+ return Response.json({ status: 401 });
+ }
+
+ // Add logic to perform protected actions
+
+ return Response.json({ message: 'This is a reply' });
+}
+```