用户授权时如何在next-auth中使用localstorage

ocebsuys  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(112)
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函数中获取它,而不是授权

kxe2p93d

kxe2p93d1#

可以在session回调中设置

async session({ session, token, user }) {
      session.accessToken = token.accessToken;
      return session;
    },

字符串
并访问客户端上的useSession和服务器上的getServerSession的会话。存储在localStorage中不安全,因为localStorage容易受到跨站点脚本(XSS)攻击

相关问题