【问题标题】:Protecting routes with getServerSideProps使用 getServerSideProps 保护路由
【发布时间】:2020-12-19 17:42:07
【问题描述】:

当用户未通过身份验证时,我一直在尝试几种方法来保护路由,但到目前为止我一直在努力解决这个问题。

尝试从 getServerSideProps 进行身份验证时最常出现的问题是我经常遇到 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client,所以我一直试图不从那里重定向并设置 redirect 布尔值,以便我可以从客户端重定向.问题是现在我收到一个错误,指出 No router instance found. you should only use "next/router" inside the client side of your app.,即使我(我认为)在客户端。

export async function getServerSideProps(ctx: ApiRoutesTypes) {

  const cookie = parseCookies(ctx);

   if (!testCookie.autho) {
     const redirectLogin = true;

     return { props: { redirectLogin } };
   }

  const query = {
    text: 'SELECT fk_users_id FROM tokens WHERE token = $1 AND status = true',
    values: [cookie],
  };
  const userId = (await db.query(query)).rows[0].fk_users_id;
    ...

  return { props: { userId } };
}
export default function Homepage({redirectLogin }){
  const router = useRouter();

  
  if (redirectLogin) {
    router.push('/login');
  }

    ...

}

有可能解决这个问题吗?如果不是,如果我的所有页面都大量使用 getServerSideProps 但还需要进行身份验证,那么重定向的最佳方法是什么?

【问题讨论】:

    标签: reactjs authentication next.js server-side-rendering


    【解决方案1】:

    使用受保护路由并将用户重定向到登录页面的最佳方法-

    使用函数设置页面的初始道具- 现在,如果 Page 是否受保护,则调用该函数时通过。

    export const authInitialProps = isProtectedRoute => ({
      req,
      res,
      query: { userId }
    }) => {
      const auth = req ? getSessionFromServer(req) : getSessionFromClient();
      const currentPath = req ? req.url : window.location.pathname;
      const user = auth.user;
      const isAnonymous = !user;
      if ( isProtectedRoute && isAnonymous && currentPath !== "/signin") {
        return redirectUser(res, "/signin");
      }
      return { auth, userId };
    };
    

    这里 isProtectedRoute 将判断路由是否受保护。 如果是这样,并且用户未登录或未登录。 如果不是——那么。

    将用户重定向到新页面,即登录。

    如果登录- 那么

    将身份验证数据传递到页面。

    现在检查用户是否登录?

    1. 服务器端检查-
    export const getSessionFromServer = req => {
      if (req.user) {
        return { user: req.user };
      }
      return {};
    };
    
    1. 客户端检查-
    Use cookies or local storage, whatever is being used by you.
    To check for the login.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2022-10-30
      • 2023-01-19
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多