【问题标题】:Route guards in Next.js + reactNext.js + react 中的路由守卫
【发布时间】:2018-11-14 04:03:04
【问题描述】:

我有一个关于 Next.js 和 React 的项目,它不使用任何库进行路由。我应该如何为未经身份验证的用户实施路由保护(受保护的路由)?或者如果cookie中没有令牌,我应该重定向它们吗?

【问题讨论】:

    标签: reactjs authentication routes next.js


    【解决方案1】:

    您可以通过一些适当的方式签入getInitialProps。逻辑评估 cookie 以决定是否重定向。

    import Router from 'next/router'
    
    const redirectToLogin = res => {  
      if (res) {
        res.writeHead(302, {Location: '/login'})
        res.end()
        res.finished = true
      } else {
        Router.push('/login')
      }
    }
    
    
    class ProtectedPage extends React.Component {
      static async getInitialProps ({req, res}) {
        // get cookie from req.headers or from document.cookie in browser
        // this cookie must not contain sensitive information!
        const profile = getProfileFromCookie(req)
        if (!profile) {
          redirectToLogin(res)
        }
      }
    }
    

    看看这个示例代码https://github.com/lipp/login-with/blob/master/example/nextjs/with-profile.js#L8(我是作者)。

    【讨论】:

    • 好主意!谢谢!
    • protectedPage 下面的所有嵌套路由呢?
    【解决方案2】:

    我对此有很多问题,但最终成功解决了问题。

    我正在使用 apollo,我的问题是,如果用户未登录或没有特定角色,我必须在服务器上重定向。这就是它的完成方式,也许它也可以帮助你:

    import { gql } from 'apollo-boost'
    import initApollo from '~/config/init-apollo'
    import { Role } from '~/generated/apollo-components'
    import { NextPage } from '~/node_modules/next'
    import redirect from '~/utils/redirect'
    import { parseCookies } from '~/utils/with-apollo'
    
    
    const GET_USER_ROLE = gql`
        query {
            me {
                role
            }
        }
    `
    
    export default (Page: NextPage<any>, allow: Role[]) => {
      const originalGetInitialProps = Page.getInitialProps
      let pageProps = {}
    
      Page.getInitialProps = async (ctx) => {
        if (originalGetInitialProps) {
          pageProps = await originalGetInitialProps(ctx)
        }
    
        const apolloClient = initApollo(
          {},
          { getToken: () => parseCookies(ctx.req).token },
        )
    
        try {
          const { data } = await apolloClient.query({ query: GET_USER_ROLE })
    
          if (!allow.includes(data.me.role as Role)) {
            redirect(ctx, '/401')
          }
    
          return {
            ...pageProps,
          }
        } catch (e) {
          console.log('error: ', e.graphQLErrors[0])
          redirect(ctx, '/login')
        }
      }
    
      return Page
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-04
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2021-06-01
      • 2018-01-10
      • 1970-01-01
      • 2019-03-26
      相关资源
      最近更新 更多