oktaAuth not showing authenticated after login

Hey all,

I have a basic React app where oktaAuth (from the useOktaAuth hook) is not showing expected values after a successful login.

The app structure is as follows:

// App.tsx

const oktaAuth = new OktaAuth({
    issuer: `https://dev-xxx.okta.com/oauth2/default`, // hidden for privacy
    clientId: 'xxx', // hidden for privacy
    redirectUri: `${window.location.origin}/dashboard`,
 })

function App() {
   const onAuthRequired = function() {
        history.push('/signin')
    }
    return (
    <Security oktaAuth={oktaAuth} onAuthRequired={onAuthRequired} >
          <Route path={SIGNIN}>
            <SignIn />
          </Route>
          <Route path={DASHBOARD}>
            <Dashboard />
        </Route>
    </Security>
    )
}
// SignIn.tsx
function SignIn() {
    const { oktaAuth } =  useOktaAuth();

    const [username, setUsername] = useState<string | undefined>('');
    const [password, setPassword] = useState<string | undefined>('');


    const handleSubmit = (e:{[key:string]:any}) => {
        e.preventDefault();
        if (!username || !password) return;

        oktaAuth.signInWithCredentials({ username, password })
        .then((res) => {
          const { sessionToken } = res;
          if (res.status === 'SUCCESS') {
            oktaAuth.session.setCookieAndRedirect(sessionToken, `${window.location.origin}/dashboard`);
          }
        })
        .catch((err) => console.log('Found an error', err));
      };

    return (
    <div className={classes.page}>
       <FormBox title="Sign In" onSubmit={handleSubmit}>
        ...
      </FormBox>
   </div>
  
    );
}

on Dashboard.tsx after successful login and redirect, we log oktaAuth as follows:

    const { authState, oktaAuth } = useOktaAuth();
    console.log( authState)

however the values are

{isPending: true, isAuthenticated: false, idToken: null, accessToken: null, refreshToken: null}accessToken: nullidToken: nullisAuthenticated: falseisPending: truerefreshToken: null__proto__: Object
{accessToken: undefined, idToken: undefined, refreshToken: undefined, isPending: false, isAuthenticated: false}accessToken: undefinedidToken: undefinedisAuthenticated: falseisPending: falserefreshToken: undefined__proto__: Object

I can see that there are no cookies set locally, however they are set on https://dev-xxx.okta.com/oauth2/default.

Is something wrong with my approach?

Thank you

Hi!

At the end of signInWithRedirect and session.setSessionCookieAndRedirect, okta session cookie would be set in the user’s browser. However, the app would not have got the tokens. For obtaining tokens, you would have to use a method like token.getWithoutPrompt.

@gpadma thank you! something like

        oktaAuth.signInWithCredentials({ username, password })
        .then((res) => {
          const { sessionToken } = res;
          if (res.status === 'SUCCESS') {
            oktaAuth.token.getWithoutPrompt({
                responseType: 'id_token',
                sessionToken,
              })
              .then((res) => {
                const { tokens } = res;
                console.log('tokens', tokens)
              
                oktaAuth.tokenManager.setTokens(tokens);
                history.push('/dashboard');

              })
              .catch((err) => {
                  console.log('err', err)
              });
          }
        })
        .catch((err) => console.log('Found an error', err));

works as expected. is setCookieAndRedirect necessary for our purposes at all?

setCookieAndRedirect is not required for your use case as you are using OIDC for the integration. It is normally used for integrations which don’t support OIDC.

You can either use getWithoutPrompt or getWithRedirect. getWithRedirect is better as that doesn’t have dependency on third party cookies.

Thanks,
Raj

1 Like

How can I obtain the tokens (using the token.getWithoutPrompt ) when I’m using the method oktaAuth.signInWithRedirect()?

The method oktaAuth.signInWithRedirect() returns a promise void.

Take a look at the ref for the signInWithRedirect() method in the AuthJS docs. You’ll notice that the sample uses our handleLoginRedirect() method, which handles the token storage for you:

if (authClient.isLoginRedirect()) {
  try {
    await authClient.handleLoginRedirect();
  } catch (e) {
    // log or display error details
  }
} else if (!await authClient.isAuthenticated()) {
  // Start the browser based oidc flow, then parse tokens from the redirect callback url
  authClient.signInWithRedirect();
} else {
  // User is authenticated
}

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.