如果驗證成功,則將NextJS重新導向從登入頁面跳到儀表板頁面
P粉021854777
P粉021854777 2023-08-13 10:56:17
0
1
597
<p>透過這個範例,我可以讓nextjs重新導向到一個指定的頁面,例如登入頁面,如果有人沒有經過驗證。然而,我可以如何修改這個,以便如果用戶經過身份驗證並且頁面是類似登錄頁面的,將他們重定向到儀表板或其他頁面?有一個配置可以實現嗎?像是<code>matcher</code>會很好地維護私人URL。但是對於我不希望用戶在登入狀態下存取的特定公開URL,我該如何解決這個問題?這種情況是否可能? </p> <pre class="brush:php;toolbar:false;">import { NextRequest, NextResponse } 從 'next/server' export async function middleware(req: NextRequest, res: NextResponse) { const token = req.headers.get('token') // TODO: 從請求頭取得令牌 const userIsAuthenticated = false // TODO: 檢查使用者是否經過驗證 console.log('middleware.ts', 'token', token); if (!userIsAuthenticated) { const signinUrl = new URL('/login', req.url) return NextResponse.redirect(signinUrl) } return NextResponse.next() } // 在這裡,您可以指定此中間件函數應該運行的所有路徑 // 支援單一字串值或匹配器數組 export const config = { matcher: ['/api/auth/:path*', '/'], }</pre>
P粉021854777
P粉021854777

全部回覆(1)
P粉986937457

假設您正在使用Next-Auth進行身份驗證:

使用withAuth包裝中間件,並使用Next-Auth提供的token變數驗證會話,然後根據會話的有效性重定向到您想要的route

這是一個可能有幫助的TS程式碼:

import { NextResponse } from 'next/server';
import { withAuth, NextRequestWithAuth } from 'next-auth/middleware';

export default withAuth(function middleware (request: NextRequestWithAuth) {
    const session = request?.nextauth?.token;

    if (request.nextUrl.pathname === '/') return NextResponse.next();
    if (!session && request.nextUrl.pathname !== '/login') 
        return NextResponse.redirect(new URL('/login', request.url));
    if (session && request.nextUrl.pathname !== '/dashboard')
        return NextResponse.redirect(new URL('/dashboard', request.url));

    return NextResponse.next();
},
{
    callbacks: {
        authorized: () => true,
    },
});

export const config = {
    matcher: [
        '/((?!api|_next/static|_next/image|favicon.ico).*)',
    ],
};
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!