V1/token 400 error when token has expired

Hello all,
I have set up my application as per the example on https://www.npmjs.com/package/@okta/okta-react, with the exception that I am using PKCE.

Authentication works fine. I am able to use Okta to login and return a token.

My issue occurs once that application is started later and the token has expired. The application automatically attempts a sign in

The following in the console:

Navigated to http://localhost:3000/
localhost/:1 A cookie associated with a cross-site resource at https://okta.com/ was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
localhost/:1 A cookie associated with a cross-site resource at http://okta.com/ was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
localhost/:1 A cookie associated with a cross-site resource at https://dev-812909.okta.com/ was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
localhost/:1 A cookie associated with a cross-site resource at http://dev-812909.okta.com/ was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
authorize:42 error.errorCode: login_required, error.description: The client specified not to prompt, but the user is not logged in.
onWindowLoadHandler @ authorize:42
authorize:42 error.errorCode: login_required, error.description: The client specified not to prompt, but the user is not logged in.
onWindowLoadHandler @ authorize:42
Navigated to https://dev-812909.okta.com/login/login.htm?fromURI=/oauth2/v1/authorize/redirect?okta_key=eaGejjM10bO9D_UySfGvv6StfQcX2CSH2fIVjnsGR5w
Navigated to http://localhost:3000/implicit/callback
VM10:1 POST https://dev-812909.okta.com/oauth2/default/v1/token 400
(anonymous) @ VM10:1
(anonymous) @ VM23 0.chunk.js:71544
w @ VM23 0.chunk.js:71517
r @ VM23 0.chunk.js:71331
r @ VM23 0.chunk.js:69815
l @ VM23 0.chunk.js:72778
u @ VM23 0.chunk.js:72346
(anonymous) @ VM23 0.chunk.js:72364
r @ VM23 0.chunk.js:70534
(anonymous) @ VM23 0.chunk.js:70563
r.promiseDispatch @ VM23 0.chunk.js:70135
(anonymous) @ VM23 0.chunk.js:70562
r @ VM23 0.chunk.js:70411
e @ VM23 0.chunk.js:70402
i @ VM23 0.chunk.js:72101
s @ VM23 0.chunk.js:72129
n @ VM23 0.chunk.js:72161
postMessage (async)
a @ VM23 0.chunk.js:72165
r @ VM23 0.chunk.js:72088
V @ VM23 0.chunk.js:70436
y.then @ VM23 0.chunk.js:70561
b @ VM23 0.chunk.js:72641
(anonymous) @ VM23 0.chunk.js:69670
_callee$ @ VM23 0.chunk.js:68621
tryCatch @ VM23 0.chunk.js:119461
invoke @ VM23 0.chunk.js:119688
prototype.<computed> @ VM23 0.chunk.js:119514
step @ VM23 0.chunk.js:115403
(anonymous) @ VM23 0.chunk.js:115421
F @ VM23 0.chunk.js:116439
(anonymous) @ VM23 0.chunk.js:115400
handleAuthentication @ VM23 0.chunk.js:68713
(anonymous) @ VM23 0.chunk.js:69197
commitHookEffectList @ VM23 0.chunk.js:211642
commitPassiveHookEffects @ VM23 0.chunk.js:211675
callCallback @ VM23 0.chunk.js:189969
invokeGuardedCallbackDev @ VM23 0.chunk.js:190018
invokeGuardedCallback @ VM23 0.chunk.js:190071
flushPassiveEffectsImpl @ VM23 0.chunk.js:215011
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushPassiveEffects @ VM23 0.chunk.js:214980
performSyncWorkOnRoot @ VM23 0.chunk.js:213860
(anonymous) @ VM23 0.chunk.js:201917
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushSyncCallbackQueueImpl @ VM23 0.chunk.js:201912
flushSyncCallbackQueue @ VM23 0.chunk.js:201900
unbatchedUpdates @ VM23 0.chunk.js:214050
legacyRenderSubtreeIntoContainer @ VM23 0.chunk.js:217148
render @ VM23 0.chunk.js:217228
./src/index.js @ VM24 main.chunk.js:5699
__webpack_require__ @ VM17 bundle.js:786
fn @ VM17 bundle.js:151
1 @ VM24 main.chunk.js:6249
__webpack_require__ @ VM17 bundle.js:786
checkDeferredModules @ VM17 bundle.js:46
webpackJsonpCallback @ VM17 bundle.js:33
(anonymous) @ VM24 main.chunk.js:1
Show 29 more frames
VM23 0.chunk.js:204447 Uncaught Error: Objects are not valid as a React child (found: object with keys {name, message, errorSummary, errorCode, errorLink, errorId, errorCauses, xhr}). If you meant to render a collection of children, use an array instead.
    in p (created by LoginCallback)
    in LoginCallback (created by Context.Consumer)
    in Route (at src/index.js:15)
    in div (created by Security)
    in Security (at src/index.js:13)
    in Router (created by BrowserRouter)
    in BrowserRouter (at src/index.js:12)
    at throwOnInvalidObjectType (VM23 0.chunk.js:204447)
    at createChild (VM23 0.chunk.js:204678)
    at reconcileChildrenArray (VM23 0.chunk.js:204924)
    at reconcileChildFibers (VM23 0.chunk.js:205287)
    at reconcileChildren (VM23 0.chunk.js:207747)
    at updateHostComponent (VM23 0.chunk.js:208256)
    at beginWork$1 (VM23 0.chunk.js:209812)
    at HTMLUnknownElement.callCallback (VM23 0.chunk.js:189969)
    at Object.invokeGuardedCallbackDev (VM23 0.chunk.js:190018)
    at invokeGuardedCallback (VM23 0.chunk.js:190071)
    at beginWork$$1 (VM23 0.chunk.js:215400)
    at performUnitOfWork (VM23 0.chunk.js:214314)
    at workLoopSync (VM23 0.chunk.js:214290)
    at performSyncWorkOnRoot (VM23 0.chunk.js:213879)
    at VM23 0.chunk.js:201917
    at unstable_runWithPriority (VM23 0.chunk.js:226988)
    at runWithPriority$2 (VM23 0.chunk.js:201863)
    at flushSyncCallbackQueueImpl (VM23 0.chunk.js:201912)
    at flushSyncCallbackQueue (VM23 0.chunk.js:201900)
    at scheduleUpdateOnFiber (VM23 0.chunk.js:213317)
    at dispatchAction (VM23 0.chunk.js:206744)
    at VM23 0.chunk.js:69400
    at VM23 0.chunk.js:69124
    at Array.forEach (<anonymous>)
    at AuthService.emit (VM23 0.chunk.js:69123)
    at AuthService.emitAuthState (VM23 0.chunk.js:68729)
    at AuthService._callee$ (VM23 0.chunk.js:68694)
    at tryCatch (VM23 0.chunk.js:119461)
    at Generator.invoke [as _invoke] (VM23 0.chunk.js:119688)
    at Generator.prototype.<computed> [as throw] (VM23 0.chunk.js:119514)
    at step (VM23 0.chunk.js:115403)
    at VM23 0.chunk.js:115416
throwOnInvalidObjectType @ VM23 0.chunk.js:204447
createChild @ VM23 0.chunk.js:204678
reconcileChildrenArray @ VM23 0.chunk.js:204924
reconcileChildFibers @ VM23 0.chunk.js:205287
reconcileChildren @ VM23 0.chunk.js:207747
updateHostComponent @ VM23 0.chunk.js:208256
beginWork$1 @ VM23 0.chunk.js:209812
callCallback @ VM23 0.chunk.js:189969
invokeGuardedCallbackDev @ VM23 0.chunk.js:190018
invokeGuardedCallback @ VM23 0.chunk.js:190071
beginWork$$1 @ VM23 0.chunk.js:215400
performUnitOfWork @ VM23 0.chunk.js:214314
workLoopSync @ VM23 0.chunk.js:214290
performSyncWorkOnRoot @ VM23 0.chunk.js:213879
(anonymous) @ VM23 0.chunk.js:201917
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushSyncCallbackQueueImpl @ VM23 0.chunk.js:201912
flushSyncCallbackQueue @ VM23 0.chunk.js:201900
scheduleUpdateOnFiber @ VM23 0.chunk.js:213317
dispatchAction @ VM23 0.chunk.js:206744
(anonymous) @ VM23 0.chunk.js:69400
(anonymous) @ VM23 0.chunk.js:69124
emit @ VM23 0.chunk.js:69123
emitAuthState @ VM23 0.chunk.js:68729
_callee$ @ VM23 0.chunk.js:68694
tryCatch @ VM23 0.chunk.js:119461
invoke @ VM23 0.chunk.js:119688
prototype.<computed> @ VM23 0.chunk.js:119514
step @ VM23 0.chunk.js:115403
(anonymous) @ VM23 0.chunk.js:115416
Promise.then (async)
step @ VM23 0.chunk.js:115413
(anonymous) @ VM23 0.chunk.js:115421
F @ VM23 0.chunk.js:116439
(anonymous) @ VM23 0.chunk.js:115400
handleAuthentication @ VM23 0.chunk.js:68713
(anonymous) @ VM23 0.chunk.js:69197
commitHookEffectList @ VM23 0.chunk.js:211642
commitPassiveHookEffects @ VM23 0.chunk.js:211675
callCallback @ VM23 0.chunk.js:189969
invokeGuardedCallbackDev @ VM23 0.chunk.js:190018
invokeGuardedCallback @ VM23 0.chunk.js:190071
flushPassiveEffectsImpl @ VM23 0.chunk.js:215011
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushPassiveEffects @ VM23 0.chunk.js:214980
performSyncWorkOnRoot @ VM23 0.chunk.js:213860
(anonymous) @ VM23 0.chunk.js:201917
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushSyncCallbackQueueImpl @ VM23 0.chunk.js:201912
flushSyncCallbackQueue @ VM23 0.chunk.js:201900
unbatchedUpdates @ VM23 0.chunk.js:214050
legacyRenderSubtreeIntoContainer @ VM23 0.chunk.js:217148
render @ VM23 0.chunk.js:217228
./src/index.js @ VM24 main.chunk.js:5699
__webpack_require__ @ VM17 bundle.js:786
fn @ VM17 bundle.js:151
1 @ VM24 main.chunk.js:6249
__webpack_require__ @ VM17 bundle.js:786
checkDeferredModules @ VM17 bundle.js:46
webpackJsonpCallback @ VM17 bundle.js:33
(anonymous) @ VM24 main.chunk.js:1
Show 32 more frames
VM23 0.chunk.js:218861 The above error occurred in the <p> component:
    in p (created by LoginCallback)
    in LoginCallback (created by Context.Consumer)
    in Route (at src/index.js:15)
    in div (created by Security)
    in Security (at src/index.js:13)
    in Router (created by BrowserRouter)
    in BrowserRouter (at src/index.js:12)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries.
console.<computed> @ VM23 0.chunk.js:218861
r @ VM25 react_devtools_backend.js:6
logCapturedError @ VM23 0.chunk.js:211459
logError @ VM23 0.chunk.js:211495
update.callback @ VM23 0.chunk.js:212838
callCallback @ VM23 0.chunk.js:203547
commitUpdateEffects @ VM23 0.chunk.js:203587
commitUpdateQueue @ VM23 0.chunk.js:203577
commitLifeCycles @ VM23 0.chunk.js:211768
commitLayoutEffects @ VM23 0.chunk.js:214963
callCallback @ VM23 0.chunk.js:189969
invokeGuardedCallbackDev @ VM23 0.chunk.js:190018
invokeGuardedCallback @ VM23 0.chunk.js:190071
commitRootImpl @ VM23 0.chunk.js:214701
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
commitRoot @ VM23 0.chunk.js:214541
finishSyncRender @ VM23 0.chunk.js:213936
performSyncWorkOnRoot @ VM23 0.chunk.js:213916
(anonymous) @ VM23 0.chunk.js:201917
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushSyncCallbackQueueImpl @ VM23 0.chunk.js:201912
flushSyncCallbackQueue @ VM23 0.chunk.js:201900
scheduleUpdateOnFiber @ VM23 0.chunk.js:213317
dispatchAction @ VM23 0.chunk.js:206744
(anonymous) @ VM23 0.chunk.js:69400
(anonymous) @ VM23 0.chunk.js:69124
emit @ VM23 0.chunk.js:69123
emitAuthState @ VM23 0.chunk.js:68729
_callee$ @ VM23 0.chunk.js:68694
tryCatch @ VM23 0.chunk.js:119461
invoke @ VM23 0.chunk.js:119688
prototype.<computed> @ VM23 0.chunk.js:119514
step @ VM23 0.chunk.js:115403
(anonymous) @ VM23 0.chunk.js:115416
Promise.then (async)
step @ VM23 0.chunk.js:115413
(anonymous) @ VM23 0.chunk.js:115421
F @ VM23 0.chunk.js:116439
(anonymous) @ VM23 0.chunk.js:115400
handleAuthentication @ VM23 0.chunk.js:68713
(anonymous) @ VM23 0.chunk.js:69197
commitHookEffectList @ VM23 0.chunk.js:211642
commitPassiveHookEffects @ VM23 0.chunk.js:211675
callCallback @ VM23 0.chunk.js:189969
invokeGuardedCallbackDev @ VM23 0.chunk.js:190018
invokeGuardedCallback @ VM23 0.chunk.js:190071
flushPassiveEffectsImpl @ VM23 0.chunk.js:215011
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushPassiveEffects @ VM23 0.chunk.js:214980
performSyncWorkOnRoot @ VM23 0.chunk.js:213860
(anonymous) @ VM23 0.chunk.js:201917
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushSyncCallbackQueueImpl @ VM23 0.chunk.js:201912
flushSyncCallbackQueue @ VM23 0.chunk.js:201900
unbatchedUpdates @ VM23 0.chunk.js:214050
legacyRenderSubtreeIntoContainer @ VM23 0.chunk.js:217148
render @ VM23 0.chunk.js:217228
./src/index.js @ VM24 main.chunk.js:5699
__webpack_require__ @ VM17 bundle.js:786
fn @ VM17 bundle.js:151
1 @ VM24 main.chunk.js:6249
__webpack_require__ @ VM17 bundle.js:786
checkDeferredModules @ VM17 bundle.js:46
webpackJsonpCallback @ VM17 bundle.js:33
(anonymous) @ VM24 main.chunk.js:1
Show 38 more frames
VM23 0.chunk.js:204447 Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {name, message, errorSummary, errorCode, errorLink, errorId, errorCauses, xhr}). If you meant to render a collection of children, use an array instead.
    in p (created by LoginCallback)
    in LoginCallback (created by Context.Consumer)
    in Route (at src/index.js:15)
    in div (created by Security)
    in Security (at src/index.js:13)
    in Router (created by BrowserRouter)
    in BrowserRouter (at src/index.js:12)
    at throwOnInvalidObjectType (VM23 0.chunk.js:204447)
    at createChild (VM23 0.chunk.js:204678)
    at reconcileChildrenArray (VM23 0.chunk.js:204924)
    at reconcileChildFibers (VM23 0.chunk.js:205287)
    at reconcileChildren (VM23 0.chunk.js:207747)
    at updateHostComponent (VM23 0.chunk.js:208256)
    at beginWork$1 (VM23 0.chunk.js:209812)
    at HTMLUnknownElement.callCallback (VM23 0.chunk.js:189969)
    at Object.invokeGuardedCallbackDev (VM23 0.chunk.js:190018)
    at invokeGuardedCallback (VM23 0.chunk.js:190071)
    at beginWork$$1 (VM23 0.chunk.js:215400)
    at performUnitOfWork (VM23 0.chunk.js:214314)
    at workLoopSync (VM23 0.chunk.js:214290)
    at performSyncWorkOnRoot (VM23 0.chunk.js:213879)
    at VM23 0.chunk.js:201917
    at unstable_runWithPriority (VM23 0.chunk.js:226988)
    at runWithPriority$2 (VM23 0.chunk.js:201863)
    at flushSyncCallbackQueueImpl (VM23 0.chunk.js:201912)
    at flushSyncCallbackQueue (VM23 0.chunk.js:201900)
    at scheduleUpdateOnFiber (VM23 0.chunk.js:213317)
    at dispatchAction (VM23 0.chunk.js:206744)
    at VM23 0.chunk.js:69400
    at VM23 0.chunk.js:69124
    at Array.forEach (<anonymous>)
    at AuthService.emit (VM23 0.chunk.js:69123)
    at AuthService.emitAuthState (VM23 0.chunk.js:68729)
    at AuthService._callee$ (VM23 0.chunk.js:68694)
    at tryCatch (VM23 0.chunk.js:119461)
    at Generator.invoke [as _invoke] (VM23 0.chunk.js:119688)
    at Generator.prototype.<computed> [as throw] (VM23 0.chunk.js:119514)
    at step (VM23 0.chunk.js:115403)
    at VM23 0.chunk.js:115416
throwOnInvalidObjectType @ VM23 0.chunk.js:204447
createChild @ VM23 0.chunk.js:204678
reconcileChildrenArray @ VM23 0.chunk.js:204924
reconcileChildFibers @ VM23 0.chunk.js:205287
reconcileChildren @ VM23 0.chunk.js:207747
updateHostComponent @ VM23 0.chunk.js:208256
beginWork$1 @ VM23 0.chunk.js:209812
callCallback @ VM23 0.chunk.js:189969
invokeGuardedCallbackDev @ VM23 0.chunk.js:190018
invokeGuardedCallback @ VM23 0.chunk.js:190071
beginWork$$1 @ VM23 0.chunk.js:215400
performUnitOfWork @ VM23 0.chunk.js:214314
workLoopSync @ VM23 0.chunk.js:214290
performSyncWorkOnRoot @ VM23 0.chunk.js:213879
(anonymous) @ VM23 0.chunk.js:201917
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushSyncCallbackQueueImpl @ VM23 0.chunk.js:201912
flushSyncCallbackQueue @ VM23 0.chunk.js:201900
scheduleUpdateOnFiber @ VM23 0.chunk.js:213317
dispatchAction @ VM23 0.chunk.js:206744
(anonymous) @ VM23 0.chunk.js:69400
(anonymous) @ VM23 0.chunk.js:69124
emit @ VM23 0.chunk.js:69123
emitAuthState @ VM23 0.chunk.js:68729
_callee$ @ VM23 0.chunk.js:68694
tryCatch @ VM23 0.chunk.js:119461
invoke @ VM23 0.chunk.js:119688
prototype.<computed> @ VM23 0.chunk.js:119514
step @ VM23 0.chunk.js:115403
(anonymous) @ VM23 0.chunk.js:115416
Promise.then (async)
step @ VM23 0.chunk.js:115413
(anonymous) @ VM23 0.chunk.js:115421
F @ VM23 0.chunk.js:116439
(anonymous) @ VM23 0.chunk.js:115400
handleAuthentication @ VM23 0.chunk.js:68713
(anonymous) @ VM23 0.chunk.js:69197
commitHookEffectList @ VM23 0.chunk.js:211642
commitPassiveHookEffects @ VM23 0.chunk.js:211675
callCallback @ VM23 0.chunk.js:189969
invokeGuardedCallbackDev @ VM23 0.chunk.js:190018
invokeGuardedCallback @ VM23 0.chunk.js:190071
flushPassiveEffectsImpl @ VM23 0.chunk.js:215011
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushPassiveEffects @ VM23 0.chunk.js:214980
performSyncWorkOnRoot @ VM23 0.chunk.js:213860
(anonymous) @ VM23 0.chunk.js:201917
unstable_runWithPriority @ VM23 0.chunk.js:226988
runWithPriority$2 @ VM23 0.chunk.js:201863
flushSyncCallbackQueueImpl @ VM23 0.chunk.js:201912
flushSyncCallbackQueue @ VM23 0.chunk.js:201900
unbatchedUpdates @ VM23 0.chunk.js:214050
legacyRenderSubtreeIntoContainer @ VM23 0.chunk.js:217148
render @ VM23 0.chunk.js:217228
./src/index.js @ VM24 main.chunk.js:5699
__webpack_require__ @ VM17 bundle.js:786
fn @ VM17 bundle.js:151
1 @ VM24 main.chunk.js:6249
__webpack_require__ @ VM17 bundle.js:786
checkDeferredModules @ VM17 bundle.js:46
webpackJsonpCallback @ VM17 bundle.js:33
(anonymous) @ VM24 main.chunk.js:1
Show 32 more frames

It I then go back to the root directory and click the sign in button, the process works.

What am I missing?

Thanks in advance

Does your application support refresh_token flow?

My understanding is that is not possible / required with PKCE
https://developer.okta.com/docs/guides/refresh-tokens/get-refresh-token/

If this is incorrect, please direct me to a resource that will assist me to implement PKCE with refresh tokens

Oh, I see what you mean, my bad I didn’t pay attention to that. But let me ask you, what do you do with the token obtained from Okta? Why do you need to refresh it? Are you passing it further to the backend application?

Well, regardless, Okta suggest to use the following to obtain a renewed token refresh silently

Hi,
You are correct, that token is then used for a backend API.

However, I am having difficulty seeing how to get the refresh token in the example above.
There does not seem to be a way to change the configuration of the authorization to give that token.
Do I need to make a separate call?

It’s not the refresh token you are getting with the example given, but just a “refresh” of an access token. It’s in quotes, b/c there is no refresh per se, just a request to get a new access token.

Also not sure if it’s applicable to your situation, but if your SPA talks to your own backend, then maybe you can just replace the architecture to using your own session cookie issues by your backend, after user successfully signs into your app.

Still not winning. Refactored it as suggested and the same error
When going through the authentication process I get a 400 error with the post request to
https://dev-xxxxx.okta.com/oauth2/default/v1/token with the response {"error":"invalid_grant","error_description":"PKCE verification failed."}

If I delete the okta_token stored in local storage before I start, I do not get this error

Are you doing the whole process, starting with /authorize?

Hi,
Basic react function below:

import React, { useState, useEffect, useContext } from 'react';
import { useOktaAuth } from '@okta/okta-react';
import { Menu, Button, Spin } from 'antd';
import uuid from 'uuid/v4';

import { get } from '../../services/axiosApi';
import { AppContext } from '../contexts/AppContext';
import {
  signIn,
  signOut,
} from '../../state/actions';

function UserMenu(props) {
  const { dispatch } = useContext(AppContext);
  const { authService, authState } = useOktaAuth();
  const [showAlert, setShowAlert] = useState({});

  useEffect(() => {
    try {
      const pkceChallenge = require('pkce-challenge');
      const challenge = pkceChallenge(128);
      const params = {
        client_id: `${process.env.REACT_APP_OKTA_CLIENT_ID}`,
        response_type: 'code',
        scope: 'openid',
        redirect_uri: `${window.location.origin}/implicit/callback`,
        state: uuid(),
        code_challenge_method: 'S256',
        code_challenge: `${challenge.code_challenge}`
      };
      get(`${process.env.REACT_APP_OKTA_ORG_URL}/oauth2/default/v1/authorize`, {
        params
      }).then(response => {
        if (response && response.status !== 302) {
          setShowAlert({
            status: true,
            params: {
              message: 'Error occurred',
              description: 'Error authorizing',
              closable: true,
              type: 'error'
            }
          });
        } else {
          // eslint-disable-next-line no-console
          console.log('Valid response', response);
        }
      });
    } catch (error) {
      console.error(error);
      setShowAlert({
        status: true,
        params: {
          message: 'Error occurred',
          description: 'Error authorizing',
          closable: true,
          type: 'error'
        }
      });
    }
    if (authState.isAuthenticated) {
      const checkAuthentication = async () => {
        const userDetails = await authService.getUser();
        const idToken = await authState.accessToken;
        if (idToken) {
          dispatch(
            signIn({
              isAuthenticated: authState.isAuthenticated,
              userDetails
            })
          );
        }
      };

      checkAuthentication();
    }
  }, [authState, authService, dispatch]);

  const login = async () => {
    // redirect to '/' after login
    authService.login('/');
  };

  const logout = async () => {
    // redirect to '/' after logout
    authService.logout('/');
    dispatch(signOut);
  };

  if (authState.isPending) {
    return <Spin size='small' />;
  }

  return (
    <div>
      {authState.isAuthenticated ? (
        <Menu.Item key='signOut' {...props}>
          <Button href='#' onClick={logout} type='link'>
            Sign Out
          </Button>
        </Menu.Item>
      ) : (
        <Menu.Item key='signIn' {...props}>
          <Button href='#' onClick={login} type='link'>
            Sign In
          </Button>
        </Menu.Item>
      )}
    </div>
  );
}

export default UserMenu;

As can be seen, the useEffect hook first tries the /authorize request

The problem is that I get a CORS error.


This is despite the http://localhost:3000 being whitelisted

Hi @ian.macrae

The /authorize endpoint is not CORS enabled and, as such, requests to it will always be blocked by the browser due to Same-Origin policy.

In order to access the /authorize endpoint successfully, you can either redirect the user to Okta to get authorized or use postMessage() as exemplified here.