可以使用下面的代码示例来解决此问题:
auth.js
。代码如下:import auth0 from 'auth0-js';
class Auth {
constructor() {
this.auth0 = new auth0.WebAuth({
domain: '{your-auth0-domain}.auth0.com',
clientID: '{your-auth0-client-id}',
redirectUri: '{your-app-redirect-url}',
responseType: 'token id_token',
scope: 'openid'
});
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
this.handleAuthentication = this.handleAuthentication.bind(this);
this.isAuthenticated = this.isAuthenticated.bind(this);
}
login() {
this.auth0.authorize();
}
handleAuthentication() {
return new Promise((resolve, reject) => {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
resolve();
} else if (err) {
reject(err);
}
});
})
}
setSession(authResult) {
// Set the time that the access token will expire at
let expiresAt = JSON.stringify(
authResult.expiresIn * 1000 + new Date().getTime()
);
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('expires_at', expiresAt);
}
logout() {
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('expires_at');
this.auth0.logout({
returnTo: '{your-app-logout-url}',
clientID: '{your-auth0-client-id}'
});
}
isAuthenticated() {
let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}
}
export default Auth;
import React, { Component } from 'react';
import Auth from './auth.js';
const auth = new Auth();
class Logout extends Component {
componentDidMount() {
auth.logout();
}
render() {
return (
You have been logged out.
);
}
}
export default Logout;
请注意,我们在auth.js
文件中的logout
方法中,使用了