嘿,有人有这个与下一个认证,我试图使我的登录认证与下一个认证,但它一直给我这个错误,并提交后,它重定向到/api/auth/error
的形式我。
我的.env包含NEXT_PUBLIC_SECRET
和NEXTAUTH_URL
在提交表单之前,控制台显示以下错误:
我的[...nextauth]代码:
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import User from '../../utils/user';
import dbConnect from '../../lib/dbConnect';
export default NextAuth({
// Enable JSON Web Tokens since we will not store sessions in our DB
session: {
strategy: 'jwt',
},
// Here we add our login providers - this is where you could add Google or Github SSO as well
providers: [
CredentialsProvider({
type: 'credentials',
// The credentials object is what's used to generate Next Auths default login page - We will not use it however.
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
},
// Authorize callback is ran upon calling the signin function
authorize: async (credentials, req) => {
dbConnect();
// Try to find the user and also return the password field
const user = await User.findOne({ email: credentials.email }).select(
'+password'
);
if (!user) {
throw new Error('No user with a matching email was found.');
}
// Use the comparePassword method we defined in our user.js Model file to authenticate
const pwValid = await user.comparePassword(credentials.password);
if (!pwValid) {
throw new Error('Your password is invalid');
}
return user;
},
}),
],
// All of this is just to add user information to be accessible for our app in the token/session
callbacks: {
// We can pass in additional information from the user document MongoDB returns
// This could be avatars, role, display name, etc...
async jwt({ token, user }) {
if (user) {
token.user = {
_id: user._id,
email: user.email,
role: user.role,
};
}
return token;
},
// If we want to access our extra user info from sessions we have to pass it the token here to get them in sync:
session: async ({ session, token }) => {
if (token) {
session.user = token.user;
}
console.log(session);
return session;
},
},
pages: {
// Here you can define your own custom pages for login, recover password, etc.
signIn: '/login', // we are going to use a custom login page (we'll create this in just a second)
},
});
登录页面代码:
import { useState, useRef } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter } from 'next/router';
import { Box, Button, TextField } from '@mui/material';
import { Formik } from 'formik';
import * as yup from 'yup';
const initialValues = {
name: '',
password: '',
};
const userSchema = yup.object().shape({
name: yup.string().required('This is required'),
password: yup.string().required('This is required'),
});
// This goes to our signup API endpoint
async function createUser(email, password) {
const response = await fetch('/api/signup', {
method: 'POST',
body: JSON.stringify({ email, password }),
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Something went wrong!');
}
return data;
}
// This gets handled by the [...nextauth] endpoint
function AuthForm() {
const [registered, setRegistered] = useState(false);
const emailInputRef = useRef();
const passwordInputRef = useRef();
// We keep track of whether in a login / or register state
const [isLogin, setIsLogin] = useState(true);
const router = useRouter();
function switchAuthModeHandler() {
setIsLogin((prevState) => !prevState);
}
const submitHandler = async (values, { resetForm }) => {
resetForm();
const enteredEmail = values.name;
const enteredPassword = values.password;
// optional: Add validation here
if (isLogin) {
await signIn('credentials', {
email: enteredEmail,
password: enteredPassword,
redirect: false,
});
} else {
try {
const result = await createUser(enteredEmail, enteredPassword);
setRegistered(true);
} catch (error) {
console.log(error);
}
}
resetForm();
};
return (
<section className="max-w-xl mx-auto my-7">
{!registered ? (
<>
<h1>{isLogin ? 'Login' : 'Sign Up'}</h1>
<Box m="20px">
<Formik
onSubmit={submitHandler}
initialValues={initialValues}
validationSchema={userSchema}
>
{({
values,
errors,
touched,
handleBlur,
handleChange,
handleSubmit,
}) => {
return (
<form onSubmit={handleSubmit}>
<Box
display="grid"
gap="30px"
gridTemplateColumns="repeat(4, minmax(0, 1fr))"
>
<TextField
fullWidth
variant="filled"
type="text"
label="Name"
onBlur={handleBlur}
onChange={handleChange}
value={values.name}
name="name"
error={!!touched.name && !!errors.name}
helperText={touched.firstName && errors.name}
sx={{ gridColumn: 'span 2' }}
/>
<TextField
fullWidth
variant="filled"
type="password"
label="password"
onBlur={handleBlur}
onChange={handleChange}
value={values.password}
name="password"
error={!!touched.password && !!errors.password}
helperText={touched.password && errors.password}
sx={{ gridColumn: 'span 2' }}
/>
</Box>
<Box display="flex" justifyContent="end" mt="20px">
<Button
type="submit"
color="secondary"
variant="contained"
>
{isLogin ? 'Login' : 'Create Account'}
</Button>
<Button
onClick={switchAuthModeHandler}
type="button"
color="secondary"
variant="contained"
>
{isLogin
? 'No Account? Create One'
: 'Already a user? Login'}
</Button>
</Box>
</form>
);
}}
</Formik>
</Box>
</>
) : (
<div className="">
<p>You have successfully registered!</p>
<button
onClick={() => router.reload()}
className="button button-color"
>
Login Now
</button>
</div>
)}
</section>
);
}
export default AuthForm;
1条答案
按热度按时间gopyfrb31#
我通过将[... nextauth].js移动到/API/auth/修复了该问题,之前它仅位于API文件夹中