Quickstart (Vanilla JS)
-
Install NodeJS v11.3.0.
-
Make a directory for your project.
mkdir YOUR_PROJECT_NAME && cd YOUR_PROJECT_NAME
-
initialise a new npm package.
npm init -y
-
Install Express and Browserify.
npm install express npm install -g browserify
-
In the project root, create an
index.js
file containing the following.var express = require('express'); var app = express() var port = 3000 app.use(express.static(__dirname + '/frontend/')); app.get('/', (req, res) => res.sendFile(__dirname + '/frontend/index.html')); app.get('/authorize/callback', (req, res) => res.sendFile(__dirname + '/frontend/index.html')); app.listen(port, () => console.log('Server started on port: ' + port));
-
Install ibm-verify-sdk and Babel polyfill which emulates a full ES2015+ environment.
npm install ibm-verify-sdk npm install @babel/polyfill
-
In the project root, create a
client.js
file containing the following.const sdk = require('ibm-verify-sdk'); const OAuthContext = sdk.OAuthContext; const config = { tenantUrl: 'TENANT_URL', clientId: 'CLIENT_ID', redirectUri: 'http://localhost:3000/authorize/callback', scope: 'openid', flowType: 'Implicit', responseType: 'token', registrationProfileId: 'REGISTRATION_ID', storageType: sessionStorage, }; const oauthClient = new OAuthContext(config); if (window.location.pathname == '/') { if (oauthClient.isAuthenticated()) { document.body.innerHTML = '<button id="logout">Logout</button>' + '<p>Authenticated</p>'; document.getElementById('logout').onclick = () => { const urlPath = '/'; oauthClient.logout(urlPath); }; } else { document.body.innerHTML = '<button id="login">Login</button>'; document.getElementById('login').onclick = () => { const url = oauthClient.login(); window.location.replace(url); }; } } else if (window.location.pathname == '/authorize/callback') { oauthClient.handleCallback(); window.location.replace('/'); }
-
Create a directory to hold the frontend resources.
mkdir frontend
-
In the
frontend
directory, create anindex.html
file containing the following.<html> <body> <script src="/bundle.js"></script> </body> </html>
-
Compile the
client.js
file for frontend usage.browserify client.js > frontend/bundle.js
-
Start the Node server.
node index.js
-
Navigate to
http://localhost:3000
.