【问题标题】:Auth0 with React and TypeScript使用 React 和 TypeScript 的 Auth0
【发布时间】:2019-11-23 06:58:00
【问题描述】:

我目前正在尝试使用 Auth0 实现一个 React 应用程序进行身份验证,而且我是 typescript 的新手。

在我的Auth.js 中尝试了下面的代码,它工作正常,但是当我尝试将我的Auth.js 文件迁移到Auth.ts 时,我得到了带有错误的红色波浪

Auth 类型上不存在属性“历史记录”

Auth e.t.c 类型上不存在属性“userProfile”

        import auth0 from "auth0-js";
    const REDIRECT_ON_LOGIN = "redirect_on_login";
   export default class Auth {
     constructor(history) {
      this.history = history;
      this.userProfile = null;
      this.requestedScopes = "openid profile email";
      this.auth0 = new auth0.WebAuth({
      domain: process.env.REACT_APP_AUTH0_DOMAIN,
      clientID: process.env.REACT_APP_AUTH0_CLIENT_ID,
      redirectUri: process.env.REACT_APP_AUTH0_CALLBACK_URL,
      audience: process.env.REACT_APP_AUTH0_AUDIENCE,
      responseType: "token id_token",
      scope: this.requestedScopes
     });
    }

  login = () => {
    localStorage.setItem(
      REDIRECT_ON_LOGIN,
      JSON.stringify(this.history.location)
    );
    this.auth0.authorize();
  };

  handleAuthentication = () => {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
        const redirectLocation =
          localStorage.getItem(REDIRECT_ON_LOGIN) === "undefined"
            ? "/"
            : JSON.parse(localStorage.getItem(REDIRECT_ON_LOGIN));
        this.history.push(redirectLocation);
      } else if (err) {
        this.history.push("/");
        alert(`Error: ${err.error}. Check the console for details`);
        console.log(err);
      }
      localStorage.removeItem(REDIRECT_ON_LOGIN);
    });
  };


我希望能够使用 react & typescript 实现 auth0 身份验证

【问题讨论】:

    标签: reactjs typescript auth0


    【解决方案1】:

    你需要安装Auth0类型:

    npm i @types/auth0
    

    或者这个:

    npm i @types/auth0-js
    

    如果这些解决方案不起作用,请在您的 tsconfig.js 文件中排除 Auth0 包,如下所示:

    "exclude": [
            "node_modules/auth0-js"
        ]
    

    只需找到 Auth0 目录并将其排除。

    【讨论】:

    • 已经安装了@types/auth0-js@types/auth0-lock...仍然有同样的问题
    • 我刚刚编辑了我的答案。从打字稿路径中排除包。
    【解决方案2】:

    在打字稿中“类”也是一种类型。因此,当您使用“类”时,您正在创建两件事。

    1- javascript类函数

    2-打字稿类型

    由于类也被视为类型,因此您必须指定属性和方法的类型。

    class Auth{
      history:findTheTypeOfHistory;
      userProfile:typeofUserProfile
      .
      .
     }
    

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2020-04-04
      • 2021-04-21
      • 2016-04-02
      • 2017-05-06
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 2021-08-31
      相关资源
      最近更新 更多