1

我正在尝试Lock v11React应用程序中实现,并且在用户登录后,即使我点击了事件侦听器并且事件类型为authenticated,也不会调用回调函数来处理令牌。

这是App.jsx我正在初始化Auth0 Lock和等待authenticated事件的地方。知道为什么我的听众不工作吗?为了进一步澄清,我将debuggers 放入代码中。成功用户登录后,我确实点击了第一个debugger,但没有点击第二个。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Redirect, Route, Switch, withRouter } from 'react-router-dom';
import Auth0Lock from 'auth0-lock';

// Actions
import * as appActions from '../actions/app-actions';

// Components
import Home from './home/Home';
import Public from './public/Public';

class App extends Component {

    lock = new Auth0Lock('my_auth0_client_id', 'my_domain.auth0.com', {
        auth: {
            audience: 'https://my_backend_api_url/',
            redirectUrl: 'http://localhost:3000',
            responseType: 'token id_token',
            sso: false
        }
      });

    constructor(props) {

        super(props);
        this.onAuthenticated = this.onAuthenticated.bind(this);
        this.isAuthenticated = this.isAuthenticated.bind(this);

        this.onAuthenticated();
    }

    onAuthenticated() {
        debugger; // After successful login, I hit this debugger
        this.lock.on('authenticated', (authResult) => {
            debugger; // But I never hit this debugger
            let expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
            sessionStorage.setItem('access_token', authResult.accessToken);
            sessionStorage.setItem('id_token', authResult.idToken);
            sessionStorage.setItem('expires_at', expiresAt);

          });
    }

    isAuthenticated() {

        if(!sessionStorage.getItem("access_token") || !sessionStorage.getItem("id_token") || !sessionStorage.getItem("expires_at"))
            return false;

        const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
        return new Date().getTime() < expiresAt;
    }

    render() {

        const isAuthenticated = this.isAuthenticated();

        return (
            <div>
                <Switch>
                    <Route exact path="/" render={props => isAuthenticated ? <Home {...props} /> : <Redirect to="/public" />} />
                    <Route path="/public">
                        <Public lock={this.lock} />
                    </Route>
                </Switch>
            </div>
        );
    }
}

function mapStateToProps(state) {

    return {
        isAuthenticated: state.app.isAuthenticated
    };
}

function mapDispatchToProps(dispatch) {

    return {

        actions: bindActionCreators(appActions, dispatch)
    };
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
4

3 回答 3

2

我是 Konrad,我是 Auth0 社区工程师,让我来帮你吧!查看有关 Lock 及其第一段的文档:

https://auth0.com/docs/libraries/lock/v11/configuration

看来您需要在索引文件中初始化 Lock 并根据此文档判断:

https://auth0.com/docs/libraries/lock/v11/api#on-

侦听器应放置在初始化 Lock 的同一文件中。

于 2019-12-19T12:41:51.860 回答
0

this.lock.on('authenticated'...在 index.js 中达到index.js并使其成为全局。lock = new Auth0Lock...

或者使用 auth0 react sdk 指南:https ://auth0.com/docs/quickstart/spa/react/01-login

希望有帮助。

于 2020-01-05T06:16:48.520 回答
0

authLock对象需要在类外部初始化,因此不仅可以在索引中声明它。

然而,要在多个页面/组件中使用注销,您需要公开它。我更喜欢 redux 而不是全局变量。

如果您需要在一个地方使用该对象

const authLockOptions: Auth0LockConstructorOptions = {
  allowSignUp: false,
  languageDictionary: { title: 'empty if you don't want title' },
  theme: {
    primaryColor: '#333435',
    logo: 'https://your-logo-url.com',
  },
};
const domain = process.env.AUTH0_DOMAIN || '';
const clientId = process.env.AUTH0_CLIENT_ID || '';
const authLock = new Auth0Lock(clientId, domain, authLockOptions);

export class LoginViewClass extends React.Component<LoginViewProps<BaseProps>, LoginViewState> {
  private authLock?: Auth0LockStatic;

  constructor(props: LoginViewProps<BaseProps>) {
    super(props);

    this.initializeAuthentication();
  }

  private initializeAuthentication = (): void => {
    authLock.on('authenticated', (authResult: any) => {
      // call authentication function;
    });

    authLock.show();
  };

  render(): React.ReactNode {
    return <div className='login'></div>;
  }
}

或者,如果您需要从多个地方调用注销

// if you are using TypeScript, Auth0LockStatic is the typeof authLock object
export type YourStore = {
  authLock: Auth0LockStatic;
  // ...
};

// start the authLock when creating the DefaultStore
export const DefaultStore: YourStore = {
  authLock: new Auth0Lock(clientId, domain, authLockOptions),
  // ...
};

// in case you use reducer
const rootReducer = combineReducers({
  // other reducers
  authLock: (state = {}) => state,
});

将其添加到 redux 存储后,您可以使用mapStateToProps (react-redux)useSelector (react-redux)连接并随意使用它。

  authLock.on('authenticated', (authResult: any) => {
    // add your authentication functionality like dispatching the authentication
  });

  authLock.show();
于 2020-12-15T21:33:55.597 回答