Skip to main content

Authentication

Important note: Before you begin, make sure you have all three of our services installed and running locally..

Install session component#

You'll connect to our services using a middleware component built in react. First, navigate to your project directory and install the module.

NPM#
npm i @pearson-ux/session-middleware --save

Next, open up the index.js file located in project > src > index.js, you'll see something like this:

index.js#

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

Import the PearsonSession component and wrap it over the <App /> component.

index.js#

import PearsonSession from "@pearson-ux/session-middleware";
ReactDOM.render(
<React.StrictMode>
<PearsonSession>
<App />
</PearsonSession>
</React.StrictMode>,
document.getElementById('root')
);

Next, open up your app.js, it should look something like this:

App.js#

// Original file from create-react-app
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;

The session provides a prop to app.js called user if a user is logged in the property will return an object with the logged in user datauser:{userId:###, etc..}. If a user is not logged in, the user object will return undefined user:undefined.

We need to condition our app.js file to check to see if a user is logged in:

App.js#

import logo from './logo.svg';
import './App.css';
// pass in a props parameter to the App function
function App(props) {
// if a user exists, they're logged in and view this content
if (props.user) {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
// else they are logged out and view this content
} else {
return (
<p> Please login to continue</p>
)
}
}
export default App;

You are set, and your app is configured. You can now pass the user prop to other components, or fire off an action and use redux to save the user as a global state.