Search code examples
javascriptreactjsauthenticationidentityserver4openid-connect

Redirect to specific page after refreshing (oidc.js)


I am using .NET Core (+IdentityServer) backend along with the SPA React application.

Whenever I change the page inside my SPA application the url updates. (for example: / to /users).

The issue: Whenever I refresh the page with F5 or want to go to the specific component connected to route using url only I get the following action inside my browser:

  1. Basic state when pressing enter in the url: localhost:3000/users
  2. After pressing enter: http://localhost:3000/signin-oidc#id_token=...
  3. When the user is logged in the page redirects to the main url: localhost:3000/

So, basically I am always redirected from the current url to the main one.

How can I make the application redirect back to the localhost:3000/users on the refresh or url change using oidc-client in react? What is the best practice to allow user to be able to refresh the page (or go to the specific url) keeping in mind that the user is already authorized?


Solution

  • If I understand you right and you are using the oidc-client-js library to implement Open Id Connect then my NodeJS Code Sample may be useful to you, and the Authenticator class in particular.

    RESTORING THE PRE-REDIRECT LOCATION / DEEP LINKING

    This is managed via code like this, which is also useful if the user has bookmarked a location within your app and needs to login first:

    // Store the state when redirecting the page
    await this._userManager.signinRedirect({
        state: location.hash,
    });
    
    // Restore it afterwards - and remove tokens from the URL
    const user = await this._userManager.signinRedirectCallback();
    history.replaceState({}, document.title, user.state.hash);
    

    RELOADING THE PAGE OR OPENING A NEW TAB

    This is best managed via silent token renewal using the Authorization Server session cookie, so that there is no top level redirect.

    await this._userManager.signinSilent();
    

    RUNNING MY SAMPLE AGAINST YOUR SYSTEM

    It may help you to have something to compare against, by running the sample against your own system, by changing the details in the SPA and API config files to point to Identity Server.