React Okta, call a function before rendering SecureRoute components

Hello, suppose I have the following

class App extends Component {
  constructor(props) {
    super(props);
    this.oktaAuth = new OktaAuth({
      issuer: 'https://{yourOktaDomain}/oauth2/default',
      clientId: '{clientId}',
      redirectUri: window.location.origin + '/login/callback'
    });
    this.restoreOriginalUri = async (_oktaAuth, originalUri) => {
      props.history.replace(toRelativeUrl(originalUri || '/', window.location.origin));
    };
  }

  render() {
    return (
      <Security oktaAuth={this.oktaAuth} restoreOriginalUri={this.restoreOriginalUri} >
        <SecureRoute exact path='/a' component={ProtectedA} />
        <SecureRoute path='/' component={Protected} />
      </Security>
    );
  }
}

After authenticating by logging into okta or reloading the page from previous session, I want to be able to store the User’s email/claim in redux before rendering the component inside the SecureRoute. Is there a way to do this?

Thanks

Hello @kyo.phan,

  1. A first step is to ensure the email scope is part of your request, it should be as OktaAuth.scopes property defaults to ['openid', 'email'] .

  2. When your callback is triggered after login, you can call this.oktaAuth.token.getUserInfo() and save the user.email claim.

this.oktaAuth.token.getUserInfo()
.then(function(user) {
  // user has details about the user
})
.catch(function(err) {
  // handle OAuthError or AuthSdkError (AuthSdkError will be thrown if app is in OAuthCallback state)
});

Thank you

1 Like

Thank you for the reply. I’m familiar with that, but that’s not quite what I’m looking for.

I want the following:
Step 1) When they arrive at the website’s SecureRoute, check if they are authenticated. If they are, then load info into redux. If they aren’t redirect to okta for login, and then store info in redux after proper login.

Step 2) Display SecureRoute’s component

It seems to me I would have to attach that getUserInfo check inside every 's component at the start, which I would like to avoid. I was hoping there would be one spot where I can inject a function where it would be called upon validating that the user is authenticated.

Edit: Maybe I’m overcomplicating it.

Maybe I can just do

<Security oktaAuth={this.oktaAuth} restoreOriginalUri={this.restoreOriginalUri} >
      <SecureRoute path='/' component={Secure} />
</Security>

and then Secure component would have something like

class Secure {
	componentDidMount() {
		//store in redux
	}

	return <Switch>
		<Route exact path='/a' component={ProtectedA} />
		<Route exact path='/' component={Protected} />
	</Switch>
}

Edit #2: The solution in Edit #1 is what I was looking for.

Hello @kyo.phan,

You probably want to save the claim only for the component loaded after user sign-in, so only one function call. There is also an Okta blog post that may help:

Thank you

1 Like