Implementing OIDC authentication in React with IdentityServer4

I’m trying to set up OIDC authentication in my React app using IdentityServer4. I’ve got the basic setup working, but I’m running into some issues.

Here’s what I’ve done so far:

// Authentication.js
import React from 'react';
import { signIn, signOut, callApi } from './authService';

function AuthComponent() {
  return (
    <div>
      <button onClick={signIn}>Sign In</button>
      <button onClick={callApi}>Call API</button>
      <button onClick={signOut}>Sign Out</button>
    </div>
  );
}

// authService.js
import { UserManager } from 'oidc-client';

const config = {
  authority: 'http://localhost:5000',
  client_id: 'myapp',
  redirect_uri: 'http://localhost:3000/callback',
  response_type: 'id_token token',
  scope: 'openid profile api1'
};

const userManager = new UserManager(config);

export function signIn() {
  userManager.signinRedirect();
}

export function signOut() {
  userManager.signoutRedirect();
}

export function callApi() {
  // API call logic here
}

When I click Sign In, I get redirected to the login page and back to my app. But the user doesn’t seem to be logged in properly. The API calls aren’t working either.

Am I missing something? How can I properly handle the callback and manage the user’s session in React? Any tips or resources would be really helpful!

I’ve implemented OIDC authentication with IdentityServer4 in React, and there are a few key points to consider. First, ensure you’re handling the callback correctly. You’ll need a separate component for the callback route that processes the authentication response. Also, make sure you’re storing the user’s session information properly. After a successful login, you should save the user’s data and tokens in a secure storage mechanism, like HTTP-only cookies or encrypted local storage. For API calls, include the access token in the Authorization header by creating an axios instance or a custom fetch wrapper. Lastly, implement a silent refresh mechanism to keep the session alive by periodically checking the token’s expiration and refreshing it in the background. Thoroughly test your authentication flow, including error scenarios and token renewal processes.

Ooh, interesting project! Have u considered using a library like react-oidc-context? It can simplify the auth flow a lot. Also, how r u handling token storage? Maybe try using secure httpOnly cookies? What kinda issues r u seeing with API calls? Curious to hear more about ur setup!

hey ava89, make sure ur handling the callback correctly. create a separate component for the callback route to process the auth response. also, store the user’s session info securely (like in http-only cookies). for API calls, remember to include the access token in the Authorization header. u might wanna implement a silent refresh mechanism too. good luck!