Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-multiple-token-types-array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@clerk/backend": patch
---

Fix token-type-mismatch error when using multiple `acceptsToken` values in `authenticateRequest`. When `acceptsToken` is an array containing both session and machine token types (e.g., `['session_token', 'api_key']`), the function now correctly routes to the appropriate authentication handler based on the actual token type, instead of always treating them as machine tokens.
32 changes: 32 additions & 0 deletions packages/backend/src/tokens/__tests__/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1426,6 +1426,38 @@ describe('tokens.authenticateRequest(options)', () => {
isAuthenticated: false,
});
});

test('accepts session_token when it is in acceptsToken array with machine tokens', async () => {
server.use(
http.get('https://api.clerk.test/v1/jwks', () => {
return HttpResponse.json(mockJwks);
}),
);

const request = mockRequest({ authorization: `Bearer ${mockJwt}` });
const requestState = await authenticateRequest(
request,
mockOptions({ acceptsToken: ['session_token', 'api_key'] }),
);

expect(requestState).toBeSignedIn();
});

test('accepts api_key when it is in acceptsToken array with session_token', async () => {
server.use(
http.post(mockMachineAuthResponses.api_key.endpoint, () => {
return HttpResponse.json(mockVerificationResults.api_key);
}),
);

const request = mockRequest({ authorization: `Bearer ${mockTokens.api_key}` });
const requestState = await authenticateRequest(
request,
mockOptions({ acceptsToken: ['session_token', 'api_key'] }),
);

expect(requestState).toBeMachineAuthenticated();
});
});

describe('Token Location Validation', () => {
Expand Down
7 changes: 7 additions & 0 deletions packages/backend/src/tokens/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,13 @@ export const authenticateRequest: AuthenticateRequest = (async (
if (acceptsToken === TokenType.SessionToken) {
return authenticateRequestWithTokenInHeader();
}
// When acceptsToken is an array, route based on the actual token type
if (Array.isArray(acceptsToken)) {
if (isMachineToken(authenticateContext.tokenInHeader)) {
return authenticateMachineRequestWithTokenInHeader();
}
return authenticateRequestWithTokenInHeader();
}
return authenticateMachineRequestWithTokenInHeader();
}

Expand Down