在服务器端用req对象认证用户。

问题描述 投票:0回答:1

我正在使用Nextjs和Node-Express-Graphql做一个服务器端的认证。

我知道如果使用passportjs,一个用户对象将被放置在req对象上,开发人员可以在nextjs getInitialProps中访问这个对象来验证用户的身份。

但是,我使用Express-session作为我的中间件,当我查看我的req对象时,里面没有用户对象。当我查看我的req对象时,里面并没有用户对象,我只看到req.headers.cookie(虽然我没有设置授权头)。我只看到req对象里面有一个req.headers.cookie(虽然我没有设置授权头)。

我可以使用req.headers.cookie来验证我的用户吗? 还是我应该使用其他方法在服务器端用Nextjs来验证用户?

以下是我的代码

我不知道自己做的是否正确的那部分代码。

    const user = req.headers.cookie;

    if (!user) {
      return serverRedirect(res, "/login");
    }

withAuth.tsx的完整代码,以防有人喜欢看。

import React from "react";
import { useQuery } from "@apollo/react-hooks";

import { GET_ME_QUERY } from "../graphql/queries";
import Redirect from "./Redirect";

export default (
  WrappedComponent: any,
  options = { ssr: false },
  role: string = "guest"
) => {
  function withAuth(props: any) {
    const { data: { getMe = {} } = {}, loading, error } = useQuery(
      GET_ME_QUERY,
      {
        fetchPolicy: "network-only",
      }
    );

    if (loading) {
      return <p>Authenticating...</p>;
    }

    if (!loading && (!getMe || error) && typeof window !== "undefined") {
      return <Redirect to="/login" />;
    }

    // TODO: Check for role
    if (getMe) {
      console.log("role", role);
      // if (role !== "guest") {
      //   return <Redirect to="/" />;
      // }
      return <WrappedComponent {...props} />;
    }

    return <p>Authenticating...</p>;
  }

  if (options.ssr) {
    const serverRedirect = (res: any, to: string) => {
      res.redirect(to);
      res.end();
      return {};
    };

    withAuth.getInitialProps = async (context: any) => {
      const { req, res } = context;
      if (req) {
        //todo find req user
        console.log("withAuth req", req.headers);
        console.log("Authenticating on Server Side");

        const user = req.headers.cookie;

        if (!user) {
          return serverRedirect(res, "/login");
        }

        // todo roles
        // if (role && !role.includes(user.role)) {
        //   return serverRedirect(res, "/login");
        // }
      }

      const pageProps =
        (await WrappedComponent.getInitialProps) &&
        WrappedComponent.getInitialProps(context);
      return { ...pageProps };
    };
  }

  return withAuth;
};
express next.js express-session
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.