Reputation: 27
I am new in the next js. I tried to use next-auth for authentication but I got the below error. Does anyone help me?
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
export default NextAuth({
providers: [
CredentialsProvider({
name: 'credentials',
credentials: {},
async authorize(credentials, req) {
const payload = {
username: credentials.username,
password: credentials.password
};
const res = await fetch(credentials.signInUrl, {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json',
}
});
const user = await res.json();
if (!res.ok) {
throw new Error(user.message);
}
// If no error and we have user data, return it
if (res.ok && user) {
console.log('Next-Auth user ', user);
return user;
}
// Return null if user data could not be retrieved
return null;
}
})
// ...add more providers here
],
// secret: process.env.JWT_SECRET,
pages: {
signIn: '/auth/login',
},
callbacks: {
async jwt({ token, user, account }) {
if (account && user) {
return {
...token,
username: user.username,
idToken: user.idToken,
refreshToken: user.refreshToken,
roles: user.roles
};
}
return token;
},
async session({ session, token }) {
session.user.accessToken = token.accessToken,
session.user.refreshToken = token.refreshToken,
return Promise.resolve(session);
}
},
// Enable debug messages in the console if you are having problems
debug: process.env.NODE_ENV === 'development'
});
and the signin page /auth/signin
const handleLoginSubmit = async (e) => {
e.preventDefault();
const signInUrl = `${process.env.NEXT_PUBLIC_API_SERVICE_BASE_URL}/api/v1/User/Login`;
const res = await signIn('credentials', {
username: loginInput.username,
password: loginInput.password,
signInUrl,
redirect: false,
});
}
But I got the error POST http://localhost:3000/api/auth/callback/credentials/ 401 (Unauthorized)
No authorization applied in _app.js
export default function MyApp({ Component, pageProps }) {
if (Component.getLayout) {
return <LayoutProvider>{Component.getLayout(<Component {...pageProps} />)}</LayoutProvider>;
} else {
return (
<LayoutProvider>
<Layout>
<Component {...pageProps} />
</Layout>
</LayoutProvider>
);
}
}
Please any one expert help me.
Upvotes: 2
Views: 4231
Reputation: 69
Because authorize()
in CredentialsProvider is failed. Return null or throw error will show /api/auth/callback/credentials/ 401 (Unauthorized), it is default behavior.
Similar question Next-Auth signIn with Credentials is not working in NextJS
Upvotes: 0