用户授权时如何在下一个认证中使用localstorage

问题描述 投票:0回答:1
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无法在服务器上运行而出现错误,我在window上进行了检查,但没有帮助。

我做得对吗?我试图在 jwt 函数中获取它,而不是授权

authentication next.js local-storage next.js13 next-auth
1个回答
0
投票

可以在

session
回调中设置

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

并在客户端上使用

useSession
访问会话,在服务器上使用
getServerSession
访问会话。存储在 localStorage 中并不安全,因为
localStorage
容易受到跨站脚本(XSS)攻击

© www.soinside.com 2019 - 2024. All rights reserved.