|
| 1 | +--- |
| 2 | +'@clerk/nextjs': minor |
| 3 | +--- |
| 4 | + |
| 5 | +Introduces machine authentication, supporting four token types: `api_key`, `oauth_token`, `machine_token`, and `session_token`. For backwards compatibility, `session_token` remains the default when no token type is specified. This enables machine-to-machine authentication and use cases such as API keys and OAuth integrations. Existing applications continue to work without modification. |
| 6 | + |
| 7 | +You can specify which token types are allowed for a given route or handler using the `acceptsToken` property in the `auth()` helper, or the `token` property in the `auth.protect()` helper. Each can be set to a specific type, an array of types, or `'any'` to accept all supported tokens. |
| 8 | + |
| 9 | +Example usage in Nextjs middleware: |
| 10 | + |
| 11 | +```ts |
| 12 | +import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'; |
| 13 | + |
| 14 | +const isOAuthAccessible = createRouteMatcher(['/oauth(.*)']) |
| 15 | +const isApiKeyAccessible = createRouteMatcher(['/api(.*)']) |
| 16 | +const isMachineTokenAccessible = createRouteMatcher(['/m2m(.*)']) |
| 17 | +const isUserAccessible = createRouteMatcher(['/user(.*)']) |
| 18 | +const isAccessibleToAnyValidToken = createRouteMatcher(['/any(.*)']) |
| 19 | + |
| 20 | +export default clerkMiddleware(async (auth, req) => { |
| 21 | + if (isOAuthAccessible(req)) await auth.protect({ token: 'oauth_token' }) |
| 22 | + if (isApiKeyAccessible(req)) await auth.protect({ token: 'api_key' }) |
| 23 | + if (isMachineTokenAccessible(req)) await auth.protect({ token: 'machine_token' }) |
| 24 | + if (isUserAccessible(req)) await auth.protect({ token: 'session_token' }) |
| 25 | + |
| 26 | + if (isAccessibleToAnyValidToken(req)) await auth.protect({ token: 'any' }) |
| 27 | +}); |
| 28 | + |
| 29 | +export const config = { |
| 30 | + matcher: [ |
| 31 | + '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)', |
| 32 | + '/(api|trpc)(.*)', |
| 33 | + ], |
| 34 | +} |
| 35 | +``` |
| 36 | + |
| 37 | +Leaf node route protection: |
| 38 | + |
| 39 | +```ts |
| 40 | +import { auth } from '@clerk/nextjs/server' |
| 41 | + |
| 42 | +// In this example, we allow users and oauth tokens with the "profile" scope |
| 43 | +// to access the data. Other types of tokens are rejected. |
| 44 | +function POST(req, res) { |
| 45 | + const authObject = await auth({ acceptsToken: ['session_token', 'oauth_token'] }) |
| 46 | + |
| 47 | + if (authObject.tokenType === 'oauth_token' && |
| 48 | + !authObject.scopes?.includes('profile')) { |
| 49 | + throw new Error('Unauthorized: OAuth token missing the "profile" scope') |
| 50 | + } |
| 51 | + |
| 52 | + // get data from db using userId |
| 53 | + const data = db.select().from(user).where(eq(user.id, authObject.userId)) |
| 54 | + |
| 55 | + return { data } |
| 56 | +} |
| 57 | +``` |
0 commit comments