@iris-platform/iris-oauth2-js-sdk

Iris OAuth2 JS SDK

Usage no npm install needed!

<script type="module">
  import irisPlatformIrisOauth2JsSdk from 'https://cdn.skypack.dev/@iris-platform/iris-oauth2-js-sdk';
</script>

README

Build

iris-oauth2-js-sdk

Isomorphic Javascript toolkit for OAuth 2.0 with Iris platform

Install

From npm

npm install @iris-platform/iris-oauth2-js-sdk

Initialize - client

import { WebAuth } from '@iris-platform/iris-oauth2-js-sdk';

const webAuth = WebAuth({
      domain: config.domain,
      clientID: config.clientID,
      responseType: 'code',
      redirectURI: config.redirectURI,
      scope: 'everything',
      authServer: config.authServer
    });

The above is example of typical initialization of client side SDK. authServer field is optional and it will default to Iris production server.

Available response types are code, token, id_token, and id_token token.

Initialize - server

Sample initialization on server side. Note, currently SDK helper functions support only express.js.

serverAuth = ServerAuth({
  domain: config.domain,
  clientID: config.clientID,
  clientSecret: config.clientSecret,
  redirectURI: config.redirectURI,
  authServer: config.authServer
});

Using response type code

When using response type code you will need to initiate login from the client side that will take you to Iris Auth manager login screen. After successful login Iris Auth manager will redirect to URI that should be implemented on application server. In order to implement this flow we will need code on both client and server. Let's start with the client code first.

const webAuth = WebAuth({
      domain: config.domain,
      clientID: config.clientID,
      responseType: 'code',
      redirectURI: config.redirectURI,
      scope: 'everything',
      authServer: config.authServer
    });
    webAuth.login({ state: 'xyz' });

Above code will initialize client side of SDK and initiate login flow with response type code.

Now on the server side we will need to create basic set up with express.js. In the index.js file:

const express = require('express');
const bodyParser = require('body-parser');
const cookieSession = require('cookie-session');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(
  cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: ['victor is a cool cat']
  })
);

require('./routes/authRoutes')(app);

const PORT = process.env.PORT || 3033;
app.listen(PORT);

Since we will be using cookie to store Iris access token we also included cookie-session module.

Next we need to create route that will handle redirect from login page. In file routes/authRoutes.js add the following code:

const { ServerAuth } = require('@iris-platform/iris-oauth2-js-sdk');
const config = require('./config');

serverAuth = ServerAuth({
  domain: config.domain,
  clientID: config.clientID,
  clientSecret: config.clientSecret,
  redirectURI: config.redirectURI,
  authServer: config.authServer
});

serverAuth.serializeUser(payload => {
  return payload.access_token;
});

serverAuth.deserializeUser(payload => {
  return payload;
});

module.exports = app => {
  app.use(serverAuth.session);

  app.get(
    '/auth/iris/callback',
    serverAuth.authenticate({
      successRedirect: config.loginSuccess,
      failureRedirect: config.loginFailure,
      state: 'xyz',
      nonce: '123'
    })
  );
}

The first thing we did is to initialize server side SDK with client ID/secret, redirect URI, domain and optional auth server URL.

Two calls serializeUser and deserializeUser are used to put/retrieve access token from the req.user and req.session.user.

We are also providing session middleware that attaches user object to the request.

Finally, we handle /auth/iris/callback URI that received code from Iris auth server. Helper function authenticate takes care of entire exchange of code for access token and it will redirect to either success or failure URLs as specified above.

It is also possible to control what happens after authenticate completes code exchange for access token. If you rather not automatically redirect use the following sample code instead to introduce your own logic:

app.get(
    '/auth/iris/callback',
    serverAuth.authenticate({
      state: 'xyz',
      nonce: '123'
    }), (req, res) => {
    console.log('AUTH CHECK: ', req.auth)
    if (req.auth) {
      res.send({message: 'authed'})
      return
    }

    res.status(401).send({message: 'unauthorized'})
  }
);

Note: In order to receive authorization data in req.auth do not pass functions to serializeUser and deserializeUser. If you do req.auth will not contain any data but rather req.user will contain deserialized information you selected.

Using response type implicit

For implicit flow you initiate call to login from the client and receive redirected URL with access token and/or id token directly without the need to exchange the code. This is useful if you want to handle authentication directly in the client.

To initiate login with implicit flow call SDK with the following sample code:

import { WebAuth } from '@iris-platform/iris-oauth2-js-sdk';

.
.
.

const webAuth = WebAuth({
      domain: config.domain,
      clientID: config.clientID,
      responseType: 'id_token token',
      redirectURI: config.implicitRedirectURI,
      scope: 'openid email',
      authServer: config.authServer
    });
    webAuth.login({ state: 'xyz' });

In this case, after login is completed Iris Auth server will redirect to URL specified in redirectURI with the following sample values:

/implicit#access_token=<access_token>&expires_in=216000&id_token=<id_token>&scope=openid+email&state=xyz&token_type=Bearer