diff --git a/packages/okta-react/src/SecureRoute.js b/packages/okta-react/src/SecureRoute.js index 9606fa957..d41fff48e 100644 --- a/packages/okta-react/src/SecureRoute.js +++ b/packages/okta-react/src/SecureRoute.js @@ -12,17 +12,22 @@ import React, { useEffect } from 'react'; import { useOktaAuth } from './OktaContext'; -import { Route } from 'react-router-dom'; +import { Route, useRouteMatch } from 'react-router-dom'; const SecureRoute = ( props ) => { const { authService, authState } = useOktaAuth(); + const match = useRouteMatch(props); useEffect(() => { + // Only process logic if the route matches + if (!match) { + return; + } // Start login if and only if app has decided it is not logged inn if(!authState.isAuthenticated && !authState.isPending) { authService.login(); } - }, [authState.isPending, authState.isAuthenticated, authService]); + }, [authState.isPending, authState.isAuthenticated, authService, match]); if (!authState.isAuthenticated) { return null; diff --git a/packages/okta-react/test/e2e/harness/src/App.js b/packages/okta-react/test/e2e/harness/src/App.js index d114f0b6c..7bcf340cc 100644 --- a/packages/okta-react/test/e2e/harness/src/App.js +++ b/packages/okta-react/test/e2e/harness/src/App.js @@ -11,7 +11,7 @@ */ import React, { Component } from 'react'; -import { Route, Switch } from 'react-router-dom'; +import { Route } from 'react-router-dom'; import { withRouter } from 'react-router'; import { AuthService, Security, LoginCallback, SecureRoute } from '@okta/okta-react'; import Home from './Home'; @@ -45,14 +45,12 @@ class App extends Component { redirectUri={redirectUri} onAuthRequired={this.onAuthRequired} pkce={pkce}> - - - - - - - - + + + + + + PKCE Flow | Implicit Flow diff --git a/packages/okta-react/test/jest/secureRoute.test.js b/packages/okta-react/test/jest/secureRoute.test.js index e96ffbf82..e052cd521 100644 --- a/packages/okta-react/test/jest/secureRoute.test.js +++ b/packages/okta-react/test/jest/secureRoute.test.js @@ -132,16 +132,27 @@ describe('', () => { authState.isPending = false; }); - it('calls login()', () => { + it('calls login() if route matches', () => { mount( - + ); expect(authService.login).toHaveBeenCalled(); }); + + it('does not call login() if route does not match', () => { + mount( + + + + + + ); + expect(authService.login).not.toHaveBeenCalled(); + }); }); describe('isPending: true', () => {