首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React + NextJS保护路由

React + NextJS保护路由
EN

Stack Overflow用户
提问于 2020-08-04 16:18:28
回答 7查看 39.9K关注 0票数 17

目标:如果登录用户试图手动转到/auth/signin,我希望将他/她重定向到主页。

登录页/组件:

代码语言:javascript
运行
复制
const Signin = ({ currentUser }) => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const { doRequest, errors } = useRequest({
        url: '/api/users/signin',
        method: 'post',
        body: {
            email, password
        },
        onSuccess: () => Router.push('/')
    });

    useEffect(() => {
        const loggedUser = () => {
            if (currentUser) {
                Router.push('/');
            }
        };
        loggedUser();
    }, []);

自定义_app组件:

代码语言:javascript
运行
复制
const AppComponent = ({ Component, pageProps, currentUser }) => {
    return (
        <div>
            <Header currentUser={currentUser} />
            <Component {...pageProps} currentUser={currentUser} />
        </div>

    )
};

AppComponent.getInitialProps = async (appContext) => {
    const client = buildClient(appContext.ctx);
    const { data } = await client.get('/api/users/currentuser');
    let pageProps = {};
    if (appContext.Component.getInitialProps) {
        pageProps = await appContext.Component.getInitialProps(appContext.ctx);
    }
    return {
        pageProps,
        ...data
    }
};

export default AppComponent;

发布:

我尝试过这样做,但是这会导致轻微的延迟,因为它不会被服务器端呈现。延迟,我的意思是:在重定向之前,它显示了我不想显示的页面。

我可以使用一个加载标志或一系列如果其他条件,但这将是一个工作,什么是最好的方法/实践来处理这个问题?

是我提出的另一个解决方案:

  • I构建了一个重定向钩子:

代码语言:javascript
运行
复制
import Router from 'next/router';
export default (ctx, target) => {
    if (ctx.res) {
        // server 
        ctx.res.writeHead(303, { Location: target });
        ctx.res.end();
    } else {
        // client
        Router.push(target);
    }
}

  • ,然后我为受保护的路由制作了2个HOC(用于登录和注销用户):

代码语言:javascript
运行
复制
import React from 'react';
import redirect from './redirect';
const withAuth = (Component) => {
    return class AuthComponent extends React.Component {
        static async getInitialProps(ctx, { currentUser }) {
            if (!currentUser) {
                return redirect(ctx, "/");
            }
        }
        render() {
            return <Component {...this.props} />
        }
    }
}
export default withAuth;

  • 然后我用它包装组件以保护页面:

代码语言:javascript
运行
复制
export default withAuth(NewTicket);

有什么更好的方法来处理这个问题吗?会很感激你的帮助。

EN

回答 7

Stack Overflow用户

发布于 2020-08-04 22:15:38

回答

我真的建议看一下这些例子,看看NextJS建议如何处理这个问题。资源真的很好!

https://github.com/vercel/next.js/tree/master/examples

例如,您可以使用next-auth,这是一个开放源码的auth选项。

例子就在这里。https://github.com/vercel/next.js/tree/master/examples/with-next-auth

代码语言:javascript
运行
复制
// _app.js
import { Provider } from 'next-auth/client'
import '../styles.css'

const App = ({ Component, pageProps }) => {
  const { session } = pageProps
  return (
    <Provider options={{ site: process.env.SITE }} session={session}>
      <Component {...pageProps} />
    </Provider>
  )
}

export default App
代码语言:javascript
运行
复制
// /pages/api/auth/[...nextauth].js
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

const options = {
  site: process.env.VERCEL_URL,
  providers: [
    Providers.Email({
      // SMTP connection string or nodemailer configuration object https://nodemailer.com/
      server: process.env.EMAIL_SERVER,
      // Email services often only allow sending email from a valid/verified address
      from: process.env.EMAIL_FROM,
    }),
    // When configuring oAuth providers make sure you enabling requesting
    // permission to get the users email address (required to sign in)
    Providers.Google({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
    Providers.Facebook({
      clientId: process.env.FACEBOOK_ID,
      clientSecret: process.env.FACEBOOK_SECRET,
    }),
    Providers.Twitter({
      clientId: process.env.TWITTER_ID,
      clientSecret: process.env.TWITTER_SECRET,
    }),
    Providers.GitHub({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
  ],
  // The 'database' option should be a connection string or TypeORM
  // configuration object https://typeorm.io/#/connection-options
  //
  // Notes:
  // * You need to install an appropriate node_module for your database!
  // * The email sign in provider requires a database but OAuth providers do not
  database: process.env.DATABASE_URL,

  session: {
    // Use JSON Web Tokens for session instead of database sessions.
    // This option can be used with or without a database for users/accounts.
    // Note: `jwt` is automatically set to `true` if no database is specified.
    // jwt: false,
    // Seconds - How long until an idle session expires and is no longer valid.
    // maxAge: 30 * 24 * 60 * 60, // 30 days
    // Seconds - Throttle how frequently to write to database to extend a session.
    // Use it to limit write operations. Set to 0 to always update the database.
    // Note: This option is ignored if using JSON Web Tokens
    // updateAge: 24 * 60 * 60, // 24 hours
    // Easily add custom properties to response from `/api/auth/session`.
    // Note: This should not return any sensitive information.
    /*
    get: async (session) => {
      session.customSessionProperty = "ABC123"
      return session
    }
    */
  },

  // JSON Web Token options
  jwt: {
    // secret: 'my-secret-123', // Recommended (but auto-generated if not specified)
    // Custom encode/decode functions for signing + encryption can be specified.
    // if you want to override what is in the JWT or how it is signed.
    // encode: async ({ secret, key, token, maxAge }) => {},
    // decode: async ({ secret, key, token, maxAge }) => {},
    // Easily add custom to the JWT. It is updated every time it is accessed.
    // This is encrypted and signed by default and may contain sensitive information
    // as long as a reasonable secret is defined.
    /*
    set: async (token) => {
      token.customJwtProperty = "ABC123"
      return token
    }
    */
  },

  // Control which users / accounts can sign in
  // You can use this option in conjunction with OAuth and JWT to control which
  // accounts can sign in without having to use a database.
  allowSignin: async (user, account) => {
    // Return true if user / account is allowed to sign in.
    // Return false to display an access denied message.
    return true
  },

  // You can define custom pages to override the built-in pages
  // The routes shown here are the default URLs that will be used.
  pages: {
    // signin: '/api/auth/signin',  // Displays signin buttons
    // signout: '/api/auth/signout', // Displays form with sign out button
    // error: '/api/auth/error', // Error code passed in query string as ?error=
    // verifyRequest: '/api/auth/verify-request', // Used for check email page
    // newUser: null // If set, new users will be directed here on first sign in
  },

  // Additional options
  // secret: 'abcdef123456789' // Recommended (but auto-generated if not specified)
  // debug: true, // Use this option to enable debug messages in the console
}

const Auth = (req, res) => NextAuth(req, res, options)

export default Auth

因此,上面的选项是defo,一个服务器端呈现的应用程序,因为我们在auth中使用/api路径。如果您想要一个无服务器解决方案,您可能必须将所有东西从/api路径中提取到lambda (AWS )+网关api ()中。您所需要的只是一个连接到该api的自定义钩子。当然,你也可以用不同的方式做这件事。

下面是另一个使用firebase的示例。

https://github.com/vercel/next.js/tree/master/examples/with-firebase-authentication

另一个使用Passport.js的例子

https://github.com/vercel/next.js/tree/master/examples/with-passport

此外,您还询问了加载行为,这个示例可能会对您有所帮助。

https://github.com/vercel/next.js/tree/master/examples/with-loading

意见

定制的_app组件通常是顶级的包装器(并不完全适合这种描述的顶级_document )。

实际上,我会在_app下面一步创建一个登录组件。通常,我会在布局组件中实现这种模式,或者像上面的例子一样,使用api路径或实用程序函数来实现。

票数 13
EN

Stack Overflow用户

发布于 2021-01-17 03:23:03

下面是一个使用getServerSideProps自定义“钩子”的示例。

我正在使用react query,但是您可以使用任何数据获取工具。

代码语言:javascript
运行
复制
// /pages/login.jsx

import SessionForm from '../components/SessionForm'
import { useSessionCondition } from '../hooks/useSessionCondition'

export const getServerSideProps = useSessionCondition(false, '/app')

const Login = () => {
    return (
        <SessionForm isLogin/>
    )
}

export default Login
代码语言:javascript
运行
复制
// /hooks/useSessionCondition.js

import { QueryClient } from "react-query";
import { dehydrate } from 'react-query/hydration'
import { refreshToken } from '../utils/user_auth';

export const useSessionCondition = (
    sessionCondition = true, // whether the user should be logged in or not
    redirect = '/' // where to redirect if the condition is not met
) => {

    return async function ({ req, res }) {
        const client = new QueryClient()
        await client.prefetchQuery('session', () => refreshToken({ headers: req.headers }))
        const data = client.getQueryData('session')

        if (!data === sessionCondition) {
            return {
                redirect: {
                    destination: redirect,
                    permanent: false,
                },
            }
        }

        return {
            props: {
                dehydratedState: JSON.parse(JSON.stringify(dehydrate(client)))
            },
        }
    }

}
票数 6
EN

Stack Overflow用户

发布于 2020-08-04 18:59:24

将NextJs升级到9.3+,使用getServerSideProps而不是getInitialProps。与getServerSideProps不同的是,getInitialProps只运行服务器端,并且总是运行服务器端。如果auth失败,则从getServerSideProps重定向。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63251020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档