Authentication with oidc-client.js and Identityserver4 in a React frontend Authentication with oidc-client.js and Identityserver4 in a React frontend reactjs reactjs

Authentication with oidc-client.js and Identityserver4 in a React frontend


IdentityServer4 is just a backend implementation of OIDC; so, all you need to do is implement the flow in the client using the given APIs. I don't know what oidc-client.js file is but it is most likely doing the same thing that you could have implemented yourself. The flow itself is very simple:

  1. React app prepares the request and redirects the user to the Auth server with client_id and redirect_uri (and state, nonce)
  2. IdentityServer checks if the client_id and redirect_uri match.
    • If the user is not logged in, show a login box
    • If a consent form is necessary (similar to when you login via Facebook/Google in some apps), show the necessary interactions
    • If user is authenticated and authorized, redirect the page to the redirect_uri with new parameters. In your case, you the URL will look like this: https://example.com/cb#access_token=...&id_token=...&stuff-like-nonce-and-state
  3. Now, the React app needs to parse the URL, access the values, and store the token somewhere to be used in future requests:

Easiest way to achieve the logic is to first set a route in the router that resolves into a component that will do the logic. This component can be "invisible." It doesn't even need to render anything. You can set the route like this:

<Route path="/cb" component={AuthorizeCallback} />

Then, implement OIDC client logic in AuthorizeCallback component. In the component, you just need to parse the URL. You can use location.hash to access #access_token=...&id_token=...&stuff-like-nonce-and-state part of the URL. You can use URLSearchParams or a 3rd party library like qs. Then, just store the value in somewhere (sessionStorage, localStorage, and if possible, cookies). Anything else you do is just implementation details. For example, in one of my apps, in order to remember the active page that user was on in the app, I store the value in sessionStorage and then use the value from that storage in AuthorizeCallback to redirect the user to the proper page. So, Auth server redirects to "/cb" that resolves to AuthorizeCallback and this component redirects to the desired location (or "/" if no location was set) based on where the user is.

Also, remember that if the Authorization server's session cookie is not expired, you will not need to relogin if the token is expired or deleted. This is useful if the token is expired but it can be problematic when you log out. That's why when you log out, you need to send a request to Authorization server to delete / expire the token immediately before deleting the token from your storage.