在 Nexjts 应用程序 + Chrome 扩展程序中使用 Clerk 身份验证的 API 请求身份验证问题

问题描述 投票:0回答:1

我在 Next.js 应用程序中使用 Clerk 时遇到 API 请求身份验证问题。尽管遵循了文档,我的身份验证检查还是失败,并且我收到了某些路由的 401 未经授权错误。

以下是我的设置的关键部分的简要概述:

// pages/api/openai/generate.ts
import { NextRequest, NextResponse } from 'next/server';
import OpenAI from 'openai';
import checkLimits from '@/utils/limits';
import { getAuth } from '@clerk/nextjs/server';
import { authenticate } from '@/utils/authenticate';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

export async function POST(req: NextRequest) {
  const { userId } = getAuth(req);
  if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const authResult = await authenticate(req);
  if (!authResult.isAuthenticated) return NextResponse.json(authResult, { status: 401 });

  // Additional logic...
}

// middleware.ts
import { authMiddleware } from '@clerk/nextjs/server';

const middleware = authMiddleware({
  publicRoutes: [
    '/api/auth/new-users',
    '/',
    '/api/stripe/webhook',
    '/api/auth/renew-token',
    '/api/openai/generate',
    '/contact',
    '/api/contact',
    '/api/newsletter',
    '/privacy'
  ],
  publishableKey: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
});

export default middleware;

export const config = {
  matcher: [
    '/((?!.+\\.[\\w]+$|_next).*)',
    '/dashboard',
    '/api/((?!.+\\.[\\w]+$|_next).*)',
  ],
};

尽管进行了这些配置,用户仍能在前端正确进行身份验证,但 API 请求因身份验证错误而失败。任何有关可能导致此问题的原因或如何调试它的指导将不胜感激。

谢谢!

reactjs authentication next.js saas clerk
1个回答
0
投票

你需要在中间件中使用createRouteMatcher

import { createRouteMatcher } from "@clerk/nextjs/server";

之后你可以放置你的公共路线

const isPublicRoute = createRouteMatcher(["/","/api(.*)"])
© www.soinside.com 2019 - 2024. All rights reserved.