如何在没有登录页面的情况下使用 NextAuth.js 进行身份验证(使用邮递员)

时间:2021-07-09 17:09:05

标签: javascript typescript rest next.js next-auth

到目前为止,在我的 Next.js 应用中,我已经完成了注册

我被要求使用 next-auth 和自定义凭据进行身份验证(登录)。我必须创建一个 rest API 端点:api/auth/login

我知道如何使用登录页面执行此操作(来自此 NextAuth.js Credentials Provider)。可以轻松完成[...nextauth].js(请看一看)。

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import prisma from '../../../lib/prisma'

const options = {
    providers: [
        Providers.Credentials({
            name: 'Credentials',
            credentials: {
                email: { label: "Email", type: "email", placeholder: "something@example.com" },
                password: {  label: "Password", type: "password" }
            },
            async authorize(credentials) {
                const {email, password} = credentials
                const user = await prisma.user.findFirst({ where: { email, password } })
                console.log(user);
            
                // If no error and we have user data, return it
                if (user) {
                return user
                }
                // Return null if user data could not be retrieved
                return null
          }
        })
      ]
}

export default (req, res) => NextAuth(req, res, options)

但是,问题是我的其余 API 端点 (api/auth/login) 将使用 Postman 进行命中/测试。那么,我如何才能在没有前端的情况下实现与典型的 Rest API 行为 (req-res) 相同的功能。

我被困在 /pages/api/auth/login.js 文件中:

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import prisma from '../../../lib/prisma'

const options = {
    providers: [
        Providers.Credentials({
            name: 'Credentials',
            credentials: {
                email: { label: "Email", type: "email", placeholder: "something@example.com" },
                password: {  label: "Password", type: "password" }
            },
            async authorize(credentials) {
                const {email, password} = credentials
                const user = await prisma.user.findFirst({ where: { email, password } })
                console.log(user);
            
                // If no error and we have user data, return it
                if (user) {
                return user
                }
                // Return null if user data could not be retrieved
                return null
          }
        })
      ]
}

export default async function handle(req, res) {
    if (req.method === 'POST') NextAuth(req, res, options)
}

不知道如何以一种 REST API 的方式实现这一点。

我试过一种方法:请看API resolved without sending a response for /api/auth/callback/credentials, this may result in stalled requests

0 个答案:

没有答案
相关问题