簡體   English   中英

jwt 回調中的 Next-Auth 注銷

[英]Next-Auth Signout within jwt callback

如果用戶在應用程序升級之間登錄到應用程序,那么我想在他們下次訪問時注銷用戶。

我正在從package.json中提取版本並將其存儲在 jwt/session 中,以便比較用戶從哪個版本進行身份驗證以及現在正在運行哪個版本。

// pages/api/auth/[nextauth].ts
const version = require('../../../package.json').version
import NextAuth from 'next-auth'
import { signOut } from 'next-auth/react'

export default NextAuth({
  providers: [ /*...*/ ],
  session: { strategy: 'jwt' },
  callbacks: {
    async jwt(props) {
      const { token, user, account } = props
      const isSignIn = user?.username ? true :false
      if(isSignIn) {
        token.version = version
        // ...
      }
      if (token?.version !== version) {
        await signOut()
        return {}
      }
      return token
    },
    // ...
  }
})

這有效,但它拋出錯誤

https://next-auth.js.org/errors#jwt_session_error window is not defined {
  message: 'window is not defined',
  stack: ...
  name: 'ReferenceError
}

我知道錯誤正在拋出,因為我在服務器端調用signOut function 而它本來是瀏覽器端window因此未定義 window 的錯誤。

如果不嘗試使用瀏覽器端調用(包括對 window 的引用),我還能如何調用signOut window

你不能在我收集的服務器端使用 signOut,但這是我在我的案例中使用的一個技巧。 而是嘗試從服務器端注銷返回錯誤代碼。

const version = require('../../../package.json').version
import NextAuth from 'next-auth'
import { signOut } from 'next-auth/react'

export default NextAuth({
  providers: [ /*...*/ ],
  session: { strategy: 'jwt' },
  callbacks: {
    async jwt(props) {
      const { token, user, account } = props
      const isSignIn = user?.username ? true :false
      if(isSignIn) {
        token.version = version
        // ...
      }
      if (token?.version !== version) {
        return {
        // You can ignore this if you don't need the previous data
         ...token,
        // Return an error code 
         error: "invalid-version",
        }
      }
      return token
    },
    // ...
  }
})

在安全路由周圍創建一個包裝器。 您也可以在通用布局中執行此操作。

export const Auth = ({children}) => {
  const { data: sessionData } = useSession();
  const router = useRouter();

  useEffect(() => {
    // check if the error has occurred
    if (sessionData?.user.error === "invalid-version") {
        // Sign out here
        signOut();
    }
  }, [sessionData?.user.error, router]);

  return (
    <>{children}</>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM