Skip to content

Error after Keycloak login "No matching state found in storage" #1501

@debegr92

Description

@debegr92

I try to use react-oidc-context in a small example project. Most of it based on the code of this README.md.
It seems like the onSigninCallback is not working properly and I need a second login to get the correct state, token and user info.

This is the behavior

  1. click login button (call signinRedirect() )
  2. redirected to Keycloak
  3. login with my username/password
  4. redirected back to my app and path /oauth2/callback + parameters in URL
  5. ERROR: "No matching state found in storage"
  6. (at this time, the onSignInCallback was not triggered!)
  7. click on the login button again (call signinRedirect(), exactly like the first time)
  8. without getting redirected a second time to Keycloak, onSigninCallback is triggered and I am logged in!

keycloakConfig.tsx

export const signinCallback = (_user: User | void): void => {
	console.log("onSigninCallback");
	console.log(_user);
	window.history.replaceState(
		{},
		document.title,
		window.location.pathname
	)
}

export const oidcConfig:AuthProviderProps = {
	authority: "http://127.0.0.1:7080/realms/test",
	client_id: "frontend",
	// This redirect URI needs to match exactly your configuration in Keycloak!
	//redirect_uri: "http://127.0.0.1:5173",
	redirect_uri: "http://127.0.0.1:5173/oauth2/callback",
	onSigninCallback: signinCallback
};

main.tsx

import { AuthProvider } from 'react-oidc-context';
import { oidcConfig } from './keycloakConfig.tsx';


createRoot(document.getElementById('root')!).render(
	<StrictMode>
		<AuthProvider {...oidcConfig}>
			<App />
		</AuthProvider>
	</StrictMode>,
)

App.tsx

import { useAuth } from 'react-oidc-context';

function App() {
	const {isAuthenticated, isLoading, error, user, settings, activeNavigator, removeUser, signinRedirect} = useAuth();
	console.log(settings);

    switch (activeNavigator) {
        case "signinSilent":
            return <div>Signing you in...</div>;
        case "signoutRedirect":
            return <div>Signing you out...</div>;
    }

    if (isLoading) {
        return <div>Loading...</div>;
    }

    if (isAuthenticated) {
        return (
			<div>
				Hello {user?.profile.sub}{" "}
				<p>{JSON.stringify(user)}</p>
				<button onClick={() => void removeUser()}>Log out</button>
			</div>
        );
    }

	return (
		<div>
			{(error ? <div>Oops... {error.message}</div> : <></>)}
			<button onClick={() => void signinRedirect()}>Log in</button>
		</div>
	);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions