首页 > 解决方案 > 使用 auth0 进行身份验证

问题描述

我正在为我的 reactjs 应用程序实施 auth0 授权

我已经创建了我的 auth0 帐户,并在我的 Auth.js 文件中传递了参数

我的 Index.js 和 main.js 代码如下。

我面临的问题是我无法获得this.props.auth价值。它在按钮中的 onClick 事件中引发错误以调用 Auth0:

TypeError:无法读取未定义的属性“登录”。

import auth0  from 'auth0-js';

export default class Auth {

     auth0 = new auth0.WebAuth({
     domain:"xxxxx.auth0.com",
     clientID:"xxxxxxxxxxxx",
     redirectUri:"http://localhost:3000/Callback",

     audience:"https://xxxx.auth0.com/userinfo",
     responseType:"token id_token",
     scope:"openid"

    });

    constructor(){
    this.login = this.login.bind(this);
    }

    login () {
        this.auth0.authorize();
    }
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router } from "react-router-dom";
import Auth from './Auth';


const auth= new Auth();
let state = {};
window.setState=(changes)=>{
  state = Object.assign({},state,changes);

};

/* eslint no-restricted-globals : 0 */
let initialState = {
  name :"user1",
  location :location.pathname.replace(/^\/?|\/$/g,""),
  auth

};

ReactDOM.render(
  <Router {...state}>
    <App />
  </Router>,
  document.getElementById("root")
);
window.setState(initialState);


serviceWorker.unregister();

main.js

import React, { Component } from "react";

export default class Main extends Component{
    render(){
        return(
            <div>

        <div>
            <h1> Please login here user </h1>
            <button onClick={this.props.auth.login}>Login</button>
            </div>
        </div>

        )
    }
}

标签: javascriptauthenticationauth0

解决方案


我没有看到您将该道具传递给 Main 组件。

你应该做的是

import Auth from './Auth';

const auth= new Auth();

export default class Main extends Component{
    render(){
        return(
            <div>

        <div>
            <h1> Please login here user </h1>
            <button onClick={auth.login}>Login</button>
            </div>
        </div>

        )
    }
}

推荐阅读