尝试成功登录Auth0后重定向失败

时间:2019-05-31 00:26:36

标签: reactjs react-router auth0

使用react-router和reacts上下文api,我试图在Auth0中对用户进行身份验证,然后在成功登录时将用户重定向到主页。我在路线中缺少什么?我通过使用包装应用程序并将登录和注销方法传递到树上来将上下文传递给应用程序的其余部分。当我从子组件中调用login()方法时,将调用上下文中的login方法,其中我将状态{isAuthenticated}设置为true,然后从上下文组件中调用Auth.login(),如所附代码所示

我已经搜索了Auth0文档,并设置了指向http://localhost:3000/admin/dashboard的正确回调路由

当我第一次单击页面上的登录名时,将显示适当的Auth0组件并且可以登录,但是在我输入凭据并单击登录按钮后,我将重定向回{Login}组件。如果之后我再次点击{Login}组件中的登录按钮,我会看到该页面试图重定向到我的本地路线,然后将我踢回到{Login}组件。

import auth from '../Auth/Auth'

const AuthContext = React.createContext();
const Auth = new auth();

class AuthProvider extends React.Component {
  state = { isAuthenticated: false }
  constructor() {
    super()
    this.login = this.login.bind(this)
    this.logout = this.logout.bind(this)
  }

  auth0Signin() {
    Auth.login()
  } 

  login() {
    this.setState({ isAuthenticated: true })
    this.auth0Signin()
  }

  logout() {
    Auth.logout()
    this.setState({ isAuthenticated: false })
  }

  render() {
    return (
      <AuthContext.Provider
        value={{
          isAuthenticated: this.state.isAuthenticated,
          login: this.login,
          logout: this.logout
        }}
      >
        {this.props.children}
      </AuthContext.Provider>
    )
  }
}
const AuthConsumer = AuthContext.Consumer

export { AuthProvider, AuthConsumer };


import Auth from './Auth/Auth'
import Callback from './views/components/Callback'
import { createBrowserHistory } from "history";
import React from 'react';
import "react-notification-alert/dist/animate.css";
import { Redirect, Route, Router, Switch } from "react-router-dom";
import { AuthConsumer, AuthProvider } from './providers/AuthContext';
import Login from './views/pages/Login';
import Register from './views/pages/Register'
import Dashboard from './layouts/Admin/Admin'

const auth = new Auth()
const hist = createBrowserHistory();

const handleAuthentication = (nextState, replace) => {
  if (/access_token|id_token|error/.test(nextState.location.hash)) {
    auth.handleAuthentication();
  }
}

const ProtectedRoute = ({ component: Component, ...rest }) => (
  <AuthConsumer>
    {({ isAuthenticated, login, logout}) => (
      <Route
        render={props =>
          isAuthenticated ? <Component login={login} logout={logout} isAuthenticated={isAuthenticated} {...props} /> : <Redirect to='/auth/login' />}
        {...rest}
      />
    )}
  </AuthConsumer>
)

const PublicRoute = ({ component: Component, ...rest }) => (
  <AuthConsumer>
    {({ isAuthenticated, login, logout}) => (
      <Route
        render={props =><Component login={login} logout={logout} isAuthenticated={isAuthenticated} {...props} /> }
        {...rest}
      />
    )}
  </AuthConsumer>
)

const App = () => {
  return (
    <>
      <Router history={hist}>
        <AuthProvider>
          {/* <Header /> */}
            <Switch>
              <ProtectedRoute path='/admin/dashboard' component={Dashboard} />
              <PublicRoute path='/auth/Register' component={Register} />
              <PublicRoute path='/auth/Login' component={Login} />
              <Route path="/callback" render={(props) => {
                  handleAuthentication(props);
                  return <Callback {...props} /> 
                }}/>
              <PublicRoute path='/' component={Login} />
            </Switch>
          {/* <Footer /> */}
        </AuthProvider>
      </Router>
    </>
  );
}

export default App;



import auth0 from 'auth0-js';
import { AUTH_CONFIG } from './auth0-variables';
import history from './History';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain: AUTH_CONFIG.domain,
    callbackUrl: AUTH_CONFIG.callbackUrl,
    clientID: AUTH_CONFIG.clientId,
    redirectUri: AUTH_CONFIG.redirectUri,
    responseType: 'token id_token',
    scope: 'openid'
  });

  login() {
    this.auth0.authorize();
  }
  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.getAccessToken = this.getAccessToken.bind(this);
    this.getIdToken = this.getIdToken.bind(this);
    this.renewSession = this.renewSession.bind(this);
  }

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
      } else if (err) {
        history.replace('/admin/dashboard');
        console.log(err);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

  getAccessToken() {
    return this.accessToken;
  }

  getIdToken() {
    return this.idToken;
  }

  setSession(authResult) {
    // Set isLoggedIn flag in localStorage
    localStorage.setItem('isLoggedIn', 'true');

    // Set the time that the Access Token will expire at
    let expiresAt = (authResult.expiresIn * 1000) + new Date().getTime();
    this.accessToken = authResult.accessToken;
    this.idToken = authResult.idToken;
    this.expiresAt = expiresAt;

    // navigate to the home route
    history.replace('/home');
  }

  renewSession() {
    this.auth0.checkSession({}, (err, authResult) => {
       if (authResult && authResult.accessToken && authResult.idToken) {
         this.setSession(authResult);
       } else if (err) {
         this.logout();
         console.log(err);
         alert(`Could not get a new token (${err.error}: ${err.error_description}).`);
       }
    });
  }

  logout() {
    // Remove tokens and expiry time
    this.accessToken = null;
    this.idToken = null;
    this.expiresAt = 0;

    // Remove isLoggedIn flag from localStorage
    localStorage.removeItem('isLoggedIn');

    this.auth0.logout({
      returnTo: window.location.origin
    });

    // navigate to the home route
    history.replace('/auth/login');
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = this.expiresAt;
    return new Date().getTime() < expiresAt;
  }
}

1 个答案:

答案 0 :(得分:0)

我这样做的方法是使用Auth实用程序方法中的history.replace(),然后重定向到authcheck组件,该组件将更新全局上下文状态。

import auth0 from 'auth0-js'
import history from './history';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain: 'webapp1.auth0.com',
    clientID: 'uZxUdMAsiDWeu3OrNpoi4JwJscdF5nAx',
    redirectUri: 'http://localhost:3000/callback',
    responseType: 'token id_token',
    scope: 'openid profile email'
  })

  userProfile = {}

  login = () => {
      this.auth0.authorize()
  }

  handleAuth = () => {
    this.auth0.parseHash((err, authResult) => {
      if(authResult) {
        localStorage.setItem('access_token', authResult.accessToken)
        localStorage.setItem('id_token', authResult.idToken)

        let expiresAt = JSON.stringify((authResult.expiresIn * 1000 + new Date().getTime()))
        localStorage.setItem('expiresAt', expiresAt)

        this.getProfile();
        setTimeout(() => { history.replace('/authcheck') }, 600);
      } else {
        console.log(err)
      }
    })
  }

  getAccessToken = () => {
    if(localStorage.getItem('access_token')) {
      const accessToken = localStorage.getItem('access_token')
      return accessToken
    } else {
      return null
    }
  }


  getProfile = () => {
    let accessToken = this.getAccessToken()
    if(accessToken) {
      this.auth0.client.userInfo(accessToken, (err, profile) => {
          if(profile) {
            this.userProfile = { profile }
          }
      } )
    }
  }


  logout = () => {
    localStorage.removeItem('access_token')
    localStorage.removeItem('id_token')
    localStorage.removeItem('expiresAt')
    setTimeout(() => { history.replace('/authcheck') }, 200);
  }

  isAuthenticated = () => {
    let expiresAt = JSON.parse(localStorage.getItem('expiresAt'))
    return new Date().getTime() < expiresAt
  }

}


import React, { useEffect, useContext } from 'react';
import history from './history';
import Context from './context';
import * as ACTIONS from '../store/actions/actions';
import axios from 'axios';

const AuthCheck = () => {
  const context = useContext(Context)

  const send_profile_to_db = (profile) => {
   const data = profile
   axios.post('/api/posts/userprofiletodb', data )
    .then(axios.get('/api/get/userprofilefromdb', {params: {email: profile.profile.email}})
      .then(res => context.handleAddDBProfile(res.data)) )
    }

  useEffect(() => {
    if(context.authObj.isAuthenticated()) {
      context.handleUserLogin()
      context.handleUserAddProfile(context.authObj.userProfile)
      send_profile_to_db(context.authObj.userProfile)
      history.replace('/')
    }
    else {
      context.handleUserLogout()
      context.handleUserRemoveProfile()
      history.replace('/')
      }
    }, [])

    return(
        <div>
        </div>
    )}




export default AuthCheck;

您可以在此处查看功能齐全的应用程序

https://github.com/iqbal125/react_hooks_fullstack_skeleton