Auth.js
安装略
配置环境变量
其中secret可以使用openssl命令生成
openssl rand -base64 32
申请第三方认证接口
获得client id和client secrets,并配置到环境变量中的GITHUB_ID和GITHUB_SECRET
基本使用
创建登录登出端点,可以在lib下创建并在对应的api router中暴露,也可以直接在api router中创建
/lib/auth.js
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
...authConfig,
providers: [
GitHub({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}
...
/api/[...nextauth]/route.js
login page
操作数据库
在provider后面增加callback
密码hash
npm i bcryptjs
添加CredentialsProvider
const login = async (credentials) => {
try {
connectToDb();
const user = await User.findOne({ username: credentials.username });
if (!user) throw new Error("Wrong credentials!");
const isPasswordCorrect = await bcrypt.compare(
credentials.password,
user.password
);
if (!isPasswordCorrect) throw new Error("Wrong credentials!");
return user;
} catch (err) {
console.log(err);
throw new Error("Failed to login!");
}
};
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
...authConfig,
providers: [
GitHub({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
CredentialsProvider({
async authorize(credentials) {
try {
const user = await login(credentials);
return user;
} catch (err) {
return null;
}
},
}),
],
callbacks: {
async signIn({ user, account, profile }) {
if (account.provider === "github") {
connectToDb();
try {
const user = await User.findOne({ email: profile.email });
if (!user) {
const newUser = new User({
username: profile.login,
email: profile.email,
image: profile.avatar_url,
});
await newUser.save();
}
} catch (err) {
console.log(err);
return false;
}
}
return true;
},
...authConfig.callbacks,
},
});
重定向错误
当使用await signIn("credentials", { username, password });进行登录的时候会触发重定向错误,这是nextjs redirect的一个问题,可以通过抛出这个错误而非return来规避。