首页 > 解决方案 > next-auth 自定义登录表单不将用户名和密码传递给 [...nextauth].js

问题描述

我想使用自定义登录页面进行下一个身份验证

问题是我无法将数据从登录页面传递到 [...nextauth].js 。

signIn('credentials', { redirect: false, phone: phone, password: password })

可以访问 [..nextauth].js 中的提供者,但是

Providers.Credentials({...没有为从 API 获取令牌而运行。

1.[...nextauth].js

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import axios from 'axios'
import { useRouter } from 'next/router'

const providers = [
  Providers.Credentials({
    id: 'credentials',
    name: 'credentials',
    authorize: async (credentials) => {
      const user = await axios.post('MyAPI',
        {
          phone: credentials.phone,
          password: credentials.password
        },
      )
    }
  })
]
const callbacks = {
  // Getting the JWT token from API response
  async session(session, user) {
    session.accessToken = user.token
    return session
  }
}
const options = {
  providers,
  callbacks
}

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

2.signin.js

import { useState } from "react";
import { signIn, csrfToken } from 'next-auth/client';

export default function Login() {
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = async (e) => {
    // e.preventDefault();
    await signIn('credentials', { redirect: false, phone: phone, password: password })
  };


  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Phone</label>
        <input
          id="username"
          name="username"
          type="text"
          placeholder="Phone"
          onChange={(e) => setPhone(e.target.value)}
          value={phone}
        />
      </div>
      <div>
        <label>Password</label>
        <input
          id="password"
          name="password"
          type="password"
          placeholder="Password"
          onChange={(e) => setPassword(e.target.value)}
          value={password}
        />
      </div>
      <button type="submit">
        Login
      </button>
    </form>
  );
}

标签: reactjsreact-hooksnext.jsnext-auth

解决方案


在您的 中[...nextauth].js,您需要指定凭据:

...
credentials: {
 username: { label: "Username", type: "text" },
 password: {  label: "Password", type: "password" }
}
...

按照文档https://next-auth.js.org/providers/credentials


一个建议:
如果您的后端是自托管的,为什么不直接[...nextauth].js在后端运行时查询您的数据库?


推荐阅读