【问题标题】:NextAuth Credential Provider with Prisma Adapter in Next12 does nothingNext12 中带有 Prisma 适配器的 NextAuth 凭据提供程序不执行任何操作
【发布时间】:2022-01-25 04:39:21
【问题描述】:

我已经使用 NextAuth CredentialsProvider 设置了我的 Nextjs (Next12) 并使用 Prisma Adapter 将用户的会话保存在数据库中。 p>

我从 NextAuth 团队自己关注了这个 documentation。但是在我点击登录按钮后什么都没有发生

注意事项

在那之前:-

  • 我已确保先尝试从数据库中获取数据,并且效果很好。
  • 我也尝试过只使用普通的session: { jwt: true, maxAge: 30 * 24 * 60 * 60 },而不是直接使用适配器。也可以正常工作。

问题

现在,我只想知道是否可以将CredentialsProviderAdapter 一起使用?

NextAuth API

以下是 2 个示例,或者一个有效,一个无效:/pages/api/auth/[...nextauth].js

  • 工作:不使用adapter
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';

export default async function auth(req, res) {
  return await NextAuth(req, res, {
    secret: process.env.SECRET,
    adapter: PrismaAdapter(prisma),
    session: {
      jwt: true,
      maxAge: 30 * 24 * 60 * 60, // 30 days
    }
    providers: [
      CredentialsProvider({
        async authorize(credentials) {
          const user = await prisma.user.findFirst({
            where: {
                email: credentials.email,
                password: credentials.password
            }
          });

          if (user !== null)
          {
              return user;
          }
          else {
            throw new Error('User does not exists. Please make sure you insert the correct email & password.')
          }
        }
      })
    ],
    callbacks: {
      redirect: async ({ url, baseUrl }) => {
        return baseUrl
      },
      jwt: async ({ token, user, account, profile, isNewUser }) => {
        if (typeof user !== typeof undefined) token.user = user;
  
        return token
      },
      session: async ({ session, user, token }) => {
        token?.user && (session.user = token.user)
  
        return session
      }
    }
  })
}
  • 不工作:使用prisma adapter
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from '@prisma/client';
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
const prisma = new PrismaClient()

export default async function auth(req, res) {
  return await NextAuth(req, res, {
    secret: process.env.SECRET,
    adapter: PrismaAdapter(prisma),
    providers: [
      CredentialsProvider({
        async authorize(credentials) {
          const user = await prisma.user.findFirst({
            where: {
                email: credentials.email,
                password: credentials.password
            }
          });

          if (user !== null)
          {
              return user;
          }
          else {
            throw new Error('User does not exists. Please make sure you insert the correct email & password.')
          }
        }
      })
    ],
    callbacks: {
      redirect: async ({ url, baseUrl }) => {
        return baseUrl
      },
      jwt: async ({ token, user, account, profile, isNewUser }) => {
        if (typeof user !== typeof undefined) token.user = user;
  
        return token
      },
      session: async ({ session, user, token }) => {
        token?.user && (session.user = token.user)
  
        return session
      }
    }
  })
}

Prisma 架构

这是当前的schema.prisma(来自 NextAuth 文档本身):-

  • 我已经做了npx prisma migrate dev & npx prisma generate
// 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"
  previewFeatures = ["referentialIntegrity"]
}

datasource db {
  provider             = "mysql"
  url                  = env("DATABASE_URL")
  // shadowDatabaseUrl    = env("SHADOW_URL")
  referentialIntegrity = "prisma"
}

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

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

  @@unique([provider, providerAccountId])
}

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

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

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

【问题讨论】:

    标签: database next.js adapter prisma next-auth


    【解决方案1】:

    根据这个doc,我刚刚发现next-auth 中的CredentialsProvider 根本不适用于adapter。您可能会找到无法或不建议与CredentialsProvider 一起使用的原因。

    这是一个额外的link,您可以在其中找到有关此问题的讨论。

    【讨论】:

    • 那么,比方说,如何使用 prisma 在数据库中持久化会话?
    猜你喜欢
    • 2021-05-18
    • 2022-11-18
    • 2021-01-22
    • 2023-03-16
    • 2023-01-12
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    相关资源
    最近更新 更多