nextjs 13中间件无法正常工作

pbossiut  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(154)

我有几个页面需要用户登录。因此,我使用中间件来检查这些页面,并通过强制用户登录来查看/使用这些页面。这是我在文件中的代码:

export {default} from "next-auth/middleware";

export const config = {
    matcher: ["/api/:path*", "/new"]
}

字符串
即使用户登录并访问/new路由,他也会被再次要求签名,而预期的行为是让经过身份验证的用户使用该路由。如果使用/api/*,则会出现问题
我使用Prisma作为适配器。下面是我的next-auth配置文件:

// /api/auth/[...nextauth]/options.ts
import { prisma } from "@/lib/database";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { type NextAuthOptions } from "next-auth";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    maxAge: 30 * 60,
  },
  debug: process.env.NODE_ENV === "development" ? true : false,
  pages: {
    signIn: "/auth/login",
  },
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_CLIENT_ID as string,
      clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
};


我将此配置导入/api/auth/[...nextauth]/route.ts,如下所示:

import NextAuth from "next-auth/next";
import { authOptions } from "./options";

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };


下面是我的schema.prisma文件:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider     = "mysql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}

model Todo {
  id               String   @id @default(cuid())
  todo_name        String
  todo_description String?
  completed        Boolean? @default(false)
  createdAt        DateTime @default(now())
  updatedAt        DateTime @updatedAt
  user             User?    @relation(fields: [userId], references: [id])
  userId           String?

  @@index([userId])
}

model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String? @db.Text
  access_token      String? @db.Text
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.Text
  session_state     String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
  @@index([userId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  todos         Todo[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}


任何帮助超过这是非常感谢

q9rjltbz

q9rjltbz1#

找到了一个解决方案,它可以工作https://stackoverflow.com/a/75732207/13770585
将会话策略设置为jwt可以解决此问题
需要将此部分添加到authOptions中

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    maxAge: 30 * 60,
    strategy: "jwt", // <- this does the job
  },
  debug: process.env.NODE_ENV === "development" ? true : false,
  pages: {
    signIn: "/auth/login",
  },
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_CLIENT_ID as string,
      clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
};

字符串

相关问题