Quickstart (React JS)
-
Install Node v11.3.0
-
Initialise a React application with Create React App
// Using npx npx create-react-app YOUR_PROJECT_NAME // Using npm npm init react-app YOUR_PROJECT_NAME
-
Enter the directory and start the development server
cd YOUR_PROJECT_NAME npm start
-
Navigate to
http://localhost:3000
-
Install the IBM Verify SDK for JavaScript
npm install ibm-verify-sdk
-
In the
src
folder create a component namedlogin.jsx
import React, { Component } from 'react' export default class login extends Component { constructor (props) { super(props); this.state = { authenticated: this.props.handleIsAuthenticated() } } render() { return ( <div> { !this.state.authenticated && <button onClick={ this.props.handleLogin }>Login to SV</button> } { this.state.authenticated && <button onClick={ this.props.handleLogout }>Logout</button> } </div> ) } }
-
In the same folder, replace
App.js
with the followingimport React, { Component } from 'react'; import Login from './login'; import { OAuthContext } from 'ibm-verify-sdk'; class App extends Component { constructor(props) { super(props); this.state = { authenticated: false, config: { tenantUrl: 'https://xxxxx.ice.ibmcloud.com', clientId: 'xxxxx', redirectUri: 'http://localhost:3000/authorize/callback', scope: 'openid', flowType: 'implicit', responseType: 'token', registrationProfileId: 'xxxxx', storageType: sessionStorage } } this.oauthClient = new OAuthContext(this.state.config); this.handleLogin = this.handleLogin.bind(this); this.handleLogout = this.handleLogout.bind(this); this.handleIsAuthenticated = this.handleIsAuthenticated.bind(this); } handleLogin () { window.location.replace(this.oauthClient.login()); } handleLogout () { this.oauthClient.logout(); } handleIsAuthenticated () { return this.oauthClient.isAuthenticated(); } render() { if (window.location.pathname === '/authorize/callback') { this.oauthClient.handleResponse(); window.location.replace('/'); } return ( <Login handleLogin={ this.handleLogin } handleLogout={ this.handleLogout } handleIsAuthenticated={ this.handleIsAuthenticated } > </Login> ); } } export default App;
-
Navigate to
http://localhost:3000