【问题标题】:How to get Auth0 User object in getServerSideProps?如何在 getServerSideProps 中获取 Auth0 用户对象?
【发布时间】:2021-11-24 03:02:07
【问题描述】:

我正在尝试使用 Auth0 和 NextJS 进行用户身份验证。登录后我想访问 getServerSideProps 中的用户对象。我点击了下面的这个链接,

Stackoverflow 但是,当我尝试粘贴代码时显示打字稿错误。我在下面附上了代码和错误。请告诉我如何解决这个问题。

import { withPageAuthRequired } from '@auth0/nextjs-auth0';

  export default withPageAuthRequired(function Profile({ user, newData }) {
    return (
      <>
        <div>{user.name}</div>
      </>
     )
   });

  export const getServerSideProps = withPageAuthRequired({ 

    async getServerSideProps (context){
      return {
         props: {
           newData: "user"
         }
       }
     }
   });

错误代码:

{
   "resource": "/Users/username/Downloads/proj/projectname/pages/profile.tsx",
   "owner": "typescript",
   "code": "2345",
   "severity": 8,
   "message": "Argument of type '{ getServerSideProps(context: any): Promise<{ props: { newData: string; }; }>; }' is not assignable to parameter of type 'ComponentType<WithPageAuthRequiredProps>'.\n  Object literal may only specify known properties, and 'getServerSideProps' does not exist in type 'ComponentType<WithPageAuthRequiredProps>'.",
   "source": "ts",
   "startLineNumber": 73,
   "startColumn": 11,
   "endLineNumber": 73,
   "endColumn": 29
}

截图:

【问题讨论】:

  • 您正在导入withApiAuthRequired,但在代码中使用withPageAuthRequired,这是一个错字吗?您能否显示您正在使用的来自 @auth0/nextjs-auth0 的所有导入?
  • @juliomalves 抱歉输入错误,我已经更新了导入。
  • 您是否有意通过包装getServerSideProps 和function Profile 两次调用withPageAuthRequired?你不需要一个包装函数调用吗?
  • @DejanVasic 因为我使用的是 auth0 google login,所以我想将这些凭据保存在我的数据库中。因此,想访问serversideprops中的user对象。
  • @SriharshaK 使用 Google 或其中的任何身份验证机制应该可以正常工作,而无需额外调用 withPageAuthRequired。我将发布一些对我有用的示例代码。顺便说一句,我也在使用谷歌身份验证以及用户名/密码选项。

标签: javascript typescript next.js server-side-rendering auth0


【解决方案1】:

您只需要包装getServerSideProps。这是一个对我有用的例子:

import React, { ReactElement } from 'react';
import { getSession, withPageAuthRequired } from '@auth0/nextjs-auth0';

import db from '.';

interface Props {
  user: DbUser;   // Not the auth0 user
}

export default function Profile({ dbUser }: Props) {
  return <div>{JSON.stringify(dbUser, null, 2)}</div>;
};


export const getServerSideProps = withPageAuthRequired({
  getServerSideProps: async ({ req, res }) => {
    const auth0User = getSession(req, res);

    // Fetch the user from the db (by email)
    let user = await db.user.findUnique({ where: { email: auth0User?.user.email } });

    // You might want to move the creation of the user somewhere else like afterCallback
    // Checkout https://auth0.github.io/nextjs-auth0/modules/handlers_callback.html
    if (!user) {
      user = db.user.create(auth0User?.user);
    } 

    return {
      props: {
        dbUser: user,
      },
    };
  },
});

【讨论】:

    【解决方案2】:

    你有example here.

    根据你的例子:

    import { getSession,withPageAuthRequired } from '@auth0/nextjs-auth0';
    
    export default function ProtectedPage({user}) {
        return (
          <>
            <div>{user.name}</div>
          </>
         )
       });
    
      export const getServerSideProps = withPageAuthRequired({
      //returnTo: '/foo',
       async getServerSideProps(ctx) {
        const session = getSession(ctx.req, ctx.res);
        //check the console of backend, you will get tokens here
        console.log(session)
        return { props: 
          { customProp: 'bar'} 
        };
       }
      });
    

    请注意getSession{user} 之间的区别:您可以在getServerSideProps 中将某些操作定义为“重定向到”。 这是什么意思?这意味着您可以重定向无法访问自定义页面的用户,例如 404

    附:你没有context,你需要有ctx变量

    【讨论】:

    • context 和 ctx 只是参数,叫什么都没关系。
    猜你喜欢
    • 2021-09-04
    • 2019-09-11
    • 2021-12-31
    • 2021-06-13
    • 2019-05-08
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    相关资源
    最近更新 更多