gpt4 book ai didi

next.js - 自定义登录页面在下一次身份验证中未正确重定向

转载 作者:行者123 更新时间:2023-12-05 03:37:08 33 4
gpt4 key购买 nike

api/[...nextauth].js

export default NextAuth({
providers: [
Providers.Credentials({
name: 'Credentials',
credentials: {
email: { label: 'E-mail', type: 'text', placeholder: 'me@gmail.com' },
password: { label: 'Password', type: 'password', placeholder: 'my password' },
},
async authorize(credentials, req) {
return { email: 'x', password: 'y'}
},
}),
]
});

pages/auth/signin.tsx

export default function SignIn() {
const [password, setPassword] = useState(null)
const [email, setEmail] = useState(null)

const onSubmit = () => {
signIn("Credentials", { email, password })
}

return (
<div>
<label>
Email
<input name="email" type="text" onChange={e => setEmail(e.target.value)} />
</label>
<label>
Password
<input name="password" type="password" onChange={e => setPassword(e.target.value)} />
</label>
<button type="submit" onClick={onSubmit}>Sign in!</button>
</div>
)
}

onSubmit 重定向到默认登录页面 /api/auth/signin?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fsignin而不是正确登录和重定向到 /。如何解决这个问题?

使用 form 标签 ( https://next-auth.js.org/configuration/pages#credentials-sign-in ) 的自定义签名表单也遇到了同样的问题

最佳答案

我找到了解决方案,但我认为文档具有误导性。

我所做的是向我的 [...nextauth].js 提供程序添加一个 id 属性:

import Credentials from 'next-auth/providers/credentials';

export default NextAuth({
providers: [
Credentials({
id: 'credentials',
name: 'Credentials',
credentials: {
username: { label: 'Adresse email', type: 'email' },
password: { label: 'Mot de passe', type: 'password' },
},
async authorize(credentials, req) {
console.log(credentials);
const user = { id: 1, name: 'Jean Dupont', email: 'jean.dupont@yopmail.com' };

if (user.id === 1) {
// Any object returned will be saved in `user` property of the JWT
return user;
}
// If you return null or false then the credentials will be rejected
return null;
// You can also Reject this callback with an Error or with a URL:
// throw new Error('error message') // Redirect to error page
// throw '/path/to/redirect' // Redirect to a URL
},
}),
],
pages: {
signIn: '/auth/login',
},
});

然后我像以前一样调用了 signIn 函数,将 name 参数替换为 id 并按照最初的要求路由到“/”

// ...
await signIn('credentials', { email, password, callbackUrl: `${window.location.origin}/` });
// ...

问题是文档没有提到在提供程序中使用 id 属性。它仅在多个提供者示例代码中提到:https://next-auth.js.org/providers/credentials#multiple-providers凭证提供程序配置页面中也没有任何内容:https://next-auth.js.org/configuration/providers/credentials-provider .

关于next.js - 自定义登录页面在下一次身份验证中未正确重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69424685/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com