那里!我想將第一個螢屏配置為登錄頁面。但是,在登錄后,我們希望阻止用戶在使用 cookie 值確認登錄后進入登錄頁面。組態檔如下,請問如何解決?
next.config.js
module.exports = {
async redirects() {
return [
{
source: "/",
destination: "/login",
permanent: false,
has: [
{
type: "cookie",
key: "authorized",
value: "access_token",
},
],
},
];
},
};
uj5u.com熱心網友回復:
這在我看來是不可能的,因為在配置中我們只能有靜態值,并且每次登錄都會改變 authtoken,UI 端重定向必須從單獨的 AuthContext 處理,就像我們對 React 應用程式所做的那樣。
上述方法的另一種選擇
正在擁有一個像“授權”這樣的 cookie,它具有價值,可以說是真偽。所以我們可以檢查'authorized'是否具有'true'值,next.config 如下所示。
參考:https ://nextjs.org/docs/api-reference/next.config.js/redirects#header-cookie-and-query-matching
{
reactStrictMode: true,
async redirects() {
return [
{
source: '/',
destination: '/login',
permanent: true,
has: [
{
type: 'cookie',
key: 'authorized',
value: 'false',
},
],
},
]
},
}
uj5u.com熱心網友回復:
一種更健壯和可控的方法是使用類似nextAuth 的方法
你必須遵循兩個步驟
- 為了涵蓋服務器端和客戶端場景(用戶直接在登錄頁面上登錄,實作這兩個),您可以使用客戶端有條件地重定向
router.push,并getInitialProps在服務器端使用 302
即使用 nextAuth
import { useSession, getSession } from "next-auth/react"
export default function Page() {
const { data: session, status } = useSession()
if (status === "loading") {
return <p>Loading...</p>
}
if (status === "unauthenticated") {
return <p>Access Denied</p>
}
// Do a router.push here
}
服務器端
import { useSession, getSession } from "next-auth/react"
export default function Page() {
const { data: session } = useSession()
if (typeof window === "undefined") return null
if (session) {
// do a 302 redirect, using ctx.resShead via getInitialprops
return <p>Access Denied</p>
}
export async function getServerSideProps(context) {
return {
props: {
session: await getSession(context),
},
}
}
- 為了讓 nextAuth 獲取 cookie,將其宣告為提供者
請參閱此處的示例 - https://stackoverflow.com/a/69418553/13749957
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449443.html
