question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Always redirects to original route after successful login with idp

See original GitHub issue

Issue and Steps to Reproduce

Hi I’m trying to use react-oidc-context to authenticate with auth0 and the package is looking very promising except for one issue. Following successful authentication with auth0 I always get redirected back to the route I was on when I clicked login. The app has 2 unprotected routes /login and /public and I could be on either of those when I click login in the page header. I always get redirected to whichever of these pages I was on initially. The login button calls login from the useReactOidc hook. I want to be redirected to the /home route and have tried doing a history.push(‘/home’) before calling login().

In the case of the login page I could include logic to redirect to /home if we’re logged in as we don’t need to be there, but in the case of /public you could have a reason to be on the page if logged in or not.

I’m not really getting how the redirect_uri in the configuration fits into this, I’ve tried setting up a route for this but it never matches (<SecuredRoute path=‘/authentication/callback’ …). If anyone has any suggestions for how to redirect to a specific route upon successful login it would be greatfully appreciated, hopefully I’ve just missed something obvious. Thanks and here’s the code:

configuration.js

const tenancy = 'https://dev-xxxxxxxxxxxxxx.eu.auth0.com';
const clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

export const configuration = {
  client_name: 'My App',
  client_id: clientId,
  scope: 'openid profile',
  response_type: 'code',
  authority: `${tenancy}`,
  redirect_uri: 'http://localhost:3000/authentication/callback',
  // post_logout_redirect_uri: 'http://localhost:3000', // Auth0 uses returnTo
  silent_redirect_uri: 'http://localhost:3000/authentication/silent_callback',
  automaticSilentRenew: true,
  loadUserInfo: true,
  metadata: {
    issuer: `${tenancy}/`,
    authorization_endpoint: `${tenancy}/authorize`,
    token_endpoint: `${tenancy}/oauth/token`,
    userinfo_endpoint: `${tenancy}/userinfo`,
    end_session_endpoint: `${tenancy}/v2/logout?returnTo=${encodeURIComponent('http://localhost:3000')}&client_id=${clientId}`
  }
};

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { AuthenticationProvider, oidcLog, InMemoryWebStorage } from '@axa-fr/react-oidc-context';
import { configuration } from './configuration';

ReactDOM.render(
  <React.StrictMode>
    <AuthenticationProvider
      configuration={configuration}
      loggerLevel={oidcLog.DEBUG}
      isEnabled={true}
      callbackComponentOverride={() => (<></>)}
      UserStore={InMemoryWebStorage}>
      <App />
    </AuthenticationProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

App.js

import React from 'react';
import { useReactOidc } from '@axa-fr/react-oidc-context';
import { BrowserRouter as Router, Link, Redirect, Route, Switch } from 'react-router-dom';
import SecuredRoute from './SecuredRoute';
import { PageHeader, Space } from 'antd';

import './App.css';

const Login = () => <h3>Login Page - use the Login button top right</h3>;
const Home = () => <h3>Home Page</h3>;
const Public = () => <h3>Public Page</h3>;

const Header = () => {
  const { oidcUser, login, logout } = useReactOidc();

  return (
    <PageHeader style={{ textAlign: "right", margin: "8px" }}>
      { oidcUser ? (
        <button onClick={logout}>Log Out</button>
      ) : (
          <button onClick={login}>Log in</button>
        )}
    </PageHeader>
  );
};

const DefaultPage = () => {
  const { oidcUser } = useReactOidc();

  return (
    oidcUser ? (
      <Redirect to="/home" />
      ) : (
      <Redirect to="/login" />
    )
  );
};


const App = () => {
  return (
    <div className="App">
      <Router>
        <Header />
        <Switch>
          <Route path='/' exact component={DefaultPage} />
          <Route path='/login' component={Login} />
          <Route path='/public' component={Public} />
          <SecuredRoute path='/home' component={Home} />
          <SecuredRoute path='/authentication/callback' component={Home} />
        </Switch>
        <Space>
          <Link to="/home">Home Page (you must be logged in to access this)</Link>
          <br/>
          <Link to="/public">Public Page (you don't need to be logged in to access this)</Link>
        </Space>
      </Router>
    </div>
  );
};

export default App;

SecuredRoute.js

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { useReactOidc } from '@axa-fr/react-oidc-context';

const SecuredRoute = ({ component: Component, ...rest }) => {
  const { oidcUser } = useReactOidc();
  
  return (
    <Route {...rest} render={(props) => (
      oidcUser
        ? <Component {...props} />
        : <Redirect to={{ pathname: '/', state: { from: props.location }}} />
    )} />
  );
};

export default SecuredRoute;

Versions

“dependencies”: { “@axa-fr/react-oidc-context”: “^3.1.6”, “@axa-fr/react-oidc-context-fetch”: “^3.1.6”, “@testing-library/jest-dom”: “^5.11.5”, “@testing-library/react”: “^11.1.1”, “@testing-library/user-event”: “^12.2.0”, “antd”: “^4.8.0”, “oidc-client”: “^1.10.1”, “react”: “^17.0.1”, “react-dom”: “^17.0.1”, “react-router-dom”: “^5.2.0”, “react-scripts”: “4.0.0”, “web-vitals”: “^0.2.4” },

Screenshots

Expected

I am able to control the route to which the browser is redirected following a successful login.

Actual

I always get redirected to the route from which I initiated the login.

Additional Details

I have tried doing a history.push(‘/home’) immediately before calling the useReactOidc login function but this didn’t work. I am aware of issue #500 but no suggestions have helped so far.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
guillaume-chervetcommented, Feb 26, 2022

https://www.npmjs.com/package/@axa-fr/react-oidc-context

This is fixed in v4, you can control thé destination route after login.

Very sorry for the delay!

0reactions
guillaume-chervetcommented, Mar 5, 2022

I close the issue. Feel free to reopen it if needed.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I redirect to a specific page after a successful IdP or ...
Redirecting the user after SSO​​ You should append the RelayState parameter or goto parameter and the required redirect URL to the login URL....
Read more >
how do I redirect back to the originally-requested url after ...
That call will redirect the browser to my IdP's sign-on page, and after a successful authentication, the IdP POSTs back to my /login/callback ......
Read more >
Redirect Users - Auth0
Redirect Users. You can return users to specific pages (URLs) within your application after validating their ID Tokens (authentication).
Read more >
Redirect Automatically to SSO IdP Authentication from the ...
Description. If an instance is configured with an SSO Identity Provider (IdP) and the 'Auto-redirect IdP' option is enabled any non-logged in users...
Read more >
SamlAuthenticationHandler Challenge redirectUri
After the succesful login in the external IdP, a post is done to https://auth.dev.mydomain.nl/S... But then there is always a redirect to "/ ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found