我正在尝试Lock v11
在React
应用程序中实现,并且在用户登录后,即使我点击了事件侦听器并且事件类型为authenticated
,也不会调用回调函数来处理令牌。
这是App.jsx
我正在初始化Auth0 Lock
和等待authenticated
事件的地方。知道为什么我的听众不工作吗?为了进一步澄清,我将debugger
s 放入代码中。成功用户登录后,我确实点击了第一个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));