reactjs - 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>
);
}
解决方案
在您的 中[...nextauth].js
,您需要指定凭据:
...
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" }
}
...
按照文档https://next-auth.js.org/providers/credentials
一个建议:
如果您的后端是自托管的,为什么不直接[...nextauth].js
在后端运行时查询您的数据库?
推荐阅读
- python - 读取 csv 文件时重置 for 循环的问题
- firebase - 在 Firebase 中随机配对用户
- django - 访问 request.GET 或在 Django 的身份验证登录/注册表单中注入变量
- javascript - 反应最终表单拆分字段值
- ruby - 如何使用多个 rspec_helpers
- php - 如何为非常大的文件替换流中的字符串
- docusignapi - 请求服务器时出现 Docusign 错误,收到了不成功的 HTTP 代码,已完成响应正文:{"error":"consent_required"}
- python - Python matplotlib plot /graph从起点部分刷新
- bash - 将日期参数传递给 bash 中的 grep
- python - 在消息中获取表情符号并获取其“代码”