import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import axios from "axios";
import NextAuth from "next-auth/next";
import $api from "@/http";
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: {
label: "Email",
type: "email",
},
password: {
label: "Password",
type: "password",
},
},
async authorize(credetials) {
if (!credetials?.email || !credetials?.password) {
return null;
}
const { email, password } = credetials;
try {
const res = await axios.post("http://localhost:5000/auth/login", {
email,
password,
});
if (res.data) {
return res.data;
} else {
return null;
}
} catch (error) {
console.log(error);
return null;
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
if (typeof window !== "undefined") {
localStorage.setItem("access_token", user.tokens.access_token);
}
return { ...token, ...user };
}
return token;
},
async session({ token, session }) {
session.user = token.user;
session.tokens = token.tokens;
return session;
},
},
};
const handler = NextAuth(authOptions);
export { handler as POST, handler as GET };
字符串
我需要确保当用户登录时,我记下了进入本地存储的accessToken,我如何在这里做到这一点?
因为我得到了一个错误,由于事实上localstorage不能在服务器上运行,我检查了窗口,但它没有帮助。
我这样做对吗?我试图在jwt函数中获取它,而不是授权
1条答案
按热度按时间kxe2p93d1#
可以在
session
回调中设置字符串
并访问客户端上的
useSession
和服务器上的getServerSession
的会话。存储在localStorage中不安全,因为localStorage
容易受到跨站点脚本(XSS)攻击