为什么next-auth中间件重定向登录用户?

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

我通过Github使用next-auth进行了auth。使用Github登录后,客户端上的next-auth/react中的useSession可以正常工作。并且来自next-auth/nextgetServerSession工作正常。但是中间件总是重定向(对于登录用户和未登录用户)。
我使用的是Next.js 13和app router以及next-auth 4。
中间件是:

export { default } from 'next-auth/middleware'

export const config = { matcher: ["/path_with_auth1", "/path_with_auth2"] }

字符串
选项为:

export const options: NextAuthOptions = {
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_ID as string,
      clientSecret: process.env.GITHUB_SECRET as string,
    }),
  ],
  adapter: PrismaAdapter(prisma),
  secret: process.env.NEXTAUTH_SECRET,
};


app/API/auth/[...nextauth]/route.ts

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

const handler = NextAuth(options);

export { handler as GET, handler as POST}


我希望它只重定向未登录的用户。你能帮我吗?如何使其正确工作?

ny6fqffe

ny6fqffe1#

根据nextAuth文档,默认情况下会话策略设置为jwt,但当提供适配器时,它默认为database
对于我来说,将会话策略设置为jwt解决了这个问题。
您的选项现在应该如下所示:

export const options: NextAuthOptions = {
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_ID as string,
      clientSecret: process.env.GITHUB_SECRET as string,
    }),
  ],
  session: {
    strategy: "jwt",
  },
  adapter: PrismaAdapter(prisma),
  secret: process.env.NEXTAUTH_SECRET,
};

字符串
购买这样做,你是覆盖默认策略从数据库到jwt,因为你已经提供了一个适配器

相关问题