Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

{error: "invalid_token", errorDescription: "state does not match."} using Universal login #819

Closed
giedrius-timinskis opened this issue Aug 19, 2018 · 7 comments

Comments

@giedrius-timinskis
Copy link

giedrius-timinskis commented Aug 19, 2018

Hello. I've been reading about this issue in Auth0 forums, and under the issues in this repo. None of the solutions seem to help or apply to my situation, I'm hoping you guys can help me out.

Here is a URL to reproduce the issue:
https://uts-tkd-app2.herokuapp.com/

Here are the relevant code snippets:

Auth.js

import auth0 from 'auth0-js';
import { ROUTES } from '../constants';

// TODO: Put inConfig (ENV VARIABLES?)
const Auth0Credentials = {
  apiKey: 'PRIVATE',
  domain: 'PRIVATE',
};

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain: Auth0Credentials.domain,
    clientID: Auth0Credentials.apiKey,
    redirectUri: `${window.location.origin}${ROUTES.LOGIN_RESULT}`,
    audience: `https://${Auth0Credentials.domain}/userinfo`,
    responseType: 'token id_token',
    scope: 'openid'
  });

  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);
  }

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

  handleAuthentication() {
	// Following the docs on https://auth0.com/blog/react-router-4-practical-tutorial/
    // return new Promise((resolve, reject) => {
      this.auth0.parseHash((err, authResult) => {
        // if (err) return reject(err);
        if (err) throw err;

        console.log(authResult);
        if (!authResult || !authResult.idToken) {
          // return reject(err);
        }

        this.setSession(authResult);
        // resolve(authResult);
      });

    // });
  }

  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() {
    // Clear access token and ID token from local storage
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
  }

  isAuthenticated() {
    // Check whether the current time is past the 
    // access token's expiry time
    const expiresAt = JSON.parse(String(localStorage.getItem('expires_at')));
    return new Date().getTime() < expiresAt;
  }
}

index.tsx

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { initialize as initializePouchDB } from './utils/pouchDB';
import Auth from './utils/auth0';

import App from './App';
import registerServiceWorker from './registerServiceWorker';
import store, { history } from './store';
import './index.css';

const auth = new Auth();
initializePouchDB();

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App auth={auth} />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();

App.tsx Just render method because the rest is irrelevant

render() {
    const { props } = this;
    const auth = props.auth;

    const isLoggedIn = auth.isAuthenticated();

    return (
      <div className="App">

        <Switch>
          <Route
            path={ROUTES.LOGIN}
            exact
            component={() => <Login auth={auth} />}
          />

          <Route
            path={ROUTES.LOGIN_RESULT}
            exact
            component={() => <LoginResult
              changeRoute={props.changeRoute}
              onSuccessRoute={ROUTES.MEMBERS}
              isLoggedIn={isLoggedIn}
              auth={auth}
            />}
          />

          <Redirect exact from="/" to={isLoggedIn ? ROUTES.MEMBERS : ROUTES.LOGIN} />

          <ProtectedRoute
            path={ROUTES.MEMBERS}
            exact
            component={() => <Members
              account={props.account}
              memberData={props.memberData}
              dimensions={dimensions}
            />}
            isAuthenticated={isLoggedIn}
          />


	...

}

Login.tsx

class Login extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
  }

  render() {
    return (
      <div className="login">
        <div className="login-content">
          <img src={logo} />
          
          <button
            onClick={this.props.auth.login}
          >
            Log IN
          </button>

        </div>
      </div>
    );
  }
}

LoginResult.tsx

class LoginResult extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
  }

  componentDidMount() {
    this.props.auth.handleAuthentication(); // <---- Fails horribly
  }

  render() {
    return (
      <div className="login">
        <div className="login-content">
          <img src={logo} alt="UTS Taekwondo" />

          <div>Signing in...</div>

        </div>
      </div>
    );
  }
}

I can also share the access to codebase if needed, just need to clean up credentials and such before I do that.

One thing I noticed is that the state that is being saved in localStorage on pressing the Log in button on /login is different from URL param in the hosted page (assuming that's the issue, but I have no clue as to why this is happening).

Tested on Chrome Version 68.0.3440.106 on Windows, with Incognito mode both enabled and disabled.
I seem to experience the issue when using both SSO and manual signin/signup methods.
Using "auth0-js": "^9.7.3".

Any help would be appreciated, I've spent the last 5 hours bashing my head against this problem, trying different permutations of the same example over and over again.

Thank you!

@luisrudge
Copy link
Contributor

Hi, this doesn't look like a bug in the SDK. Looks like a bug in your code. Please reach out to our amazing support team at https://support.auth0.com so they can better assist you with your scenario.

I'd start by trying to figure it out why the state stored in localStorage is not the same as the one being sent to /authorize.

@giedrius-timinskis
Copy link
Author

giedrius-timinskis commented Aug 19, 2018

Thanks for the quick reply. Any hints as to why the state would be different? It's all being set by the Auth0 SDK from my understanding (authorize()) in this case?

@giedrius-timinskis
Copy link
Author

Hey @luisrudge so sorry to keep posting on a closed issue, but I noticed something interesting happening.

Here's what happens on the hosted page:
Initially the page hits a 302 the /authorize endpoint. On this call the state is the same as the client (NG-fJ61sEVbbQl3T0GTj2VF_GoQv53oy).
authorize_state

The next call to /login has a completely different state (HbTHlVpuZ5ejJXjs5xn7jd_ywlSKZzFk).
login_state

I assume that's where the state mismatch happens, because the client side still has the old state in localStorage.

Again, I'm sorry to bother, but it seems to me that I can't really control this state change on my side.
Thanks!

@luisrudge
Copy link
Contributor

After you log in, what state is sent back to your application? The second state is internal to Auth0 and shouldn't be taken into consideration for this issue.

Here's an example: https://brucke.club/ - if you click the "Universal Login Page" button, it will behave in the same way as your screenshot:

image

But the state that the server sends back to the application is the correct one:

image

@giedrius-timinskis
Copy link
Author

giedrius-timinskis commented Aug 20, 2018

Thank you @luisrudge, you were absolutely correct, the issue was with my code. Thanks for nudging me in the right direction!

Here's a description of my situation for people finding this issue later:

TLDR: Make sure auth0.parseHash (handleAuthentication if you're using the React Quickstart) is not called more than once in the /callback component.

In my case I was using the Router component incorrectly. I was using component prop with an anonymous function, which means that whenever the render method was called in App the Route component would re-mount. Since I was calling the handleAuthentication method in componentDidMount of the /callback component, it would be called twice in a rapid succession. On the first Callback component mount upon the handleAuthentication call, Auth0 SDK clears out the localStorage object that contains the authentication state. Then, on a second mount the same call wouldn't have access to the auth state anymore, throwing the above error.

The fix was to use the render prop of Route component to prevent the /callback component from remounting unnecessarily.

So:

<Route
    path={ROUTES.LOGIN_CALLBACK}
    exact
    component={() => <LoginCallback auth={auth}/>}
/>

to

<Route
    path={ROUTES.LOGIN_CALLBACK}
    exact
    render={(props) => <LoginCallback {...props} auth={auth}/>}
/>

@luisrudge
Copy link
Contributor

@giedrius-timinskis thanks for adding the full explanation here. I'm sure this will help people that have the same issue in the future. I'm glad you figured it out!

@kentferolino
Copy link

Thanks @giedrius-timinskis for explaining what caused the error (handleAuthentication being called more than once). Mine was a little bit different though but the problem was the same, handleAuthentication was being called more than once.

I was trying to implement hooks on all the components, and forgot to add the square bracket [] at the end of the useEffect hook that calls the handleAuthentication.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants