Skip to main content

Quickstart (Vanilla JS)

  1. Install NodeJS v11.3.0.

  2. Make a directory for your project.

    mkdir YOUR_PROJECT_NAME && cd YOUR_PROJECT_NAME
  3. initialise a new npm package.

    npm init -y
  4. Install Express and Browserify.

    npm install express
    npm install -g browserify
  5. 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));
  6. Install ibm-verify-sdk and Babel polyfill which emulates a full ES2015+ environment.

    npm install ibm-verify-sdk
    npm install @babel/polyfill
  7. 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('/');
    }
  8. Create a directory to hold the frontend resources.

    mkdir frontend
  9. In the frontend directory, create an index.html file containing the following.

    <html>
    <body>    
        <script src="/bundle.js"></script>
    </body>
    </html>
  10. Compile the client.js file for frontend usage.

    browserify client.js > frontend/bundle.js
  11. Start the Node server.

    node index.js
  12. Navigate to http://localhost:3000.