How To: Sign into your Single Page JavaScript App with The Identity Hub

Summary

In this topic you will learn the how to allow users to login to your Single Page Application using The Identity Hub - {tenant}.

Contents

  • Objectives
  • Summary of Steps
  • Step 1 - Register your SPA as an App.
  • Step 2 - Add logic to retrieve the token.
  • Step 3 - Use the token to call an API.
  • Troubleshooting

Objectives

  • Secure login to your SPA site using The Identity Hub - {tenant}

Summary of Steps

  • Step 1 - Register your SPA as an App
  • Step 2 - Add logic to sign in.
  • Step 3 - Add logic to retrieve the token.
  • Step 4 - Use the token to call an API.

Step 1 - Register your SPA as an App

In this step you will register your SPA as an App at The Identity Hub.

For more information about Apps see How To: What is an App?.

  • Navigate to the Apps Admin Page and click on New.

  • Provide the following information
    • Name: The name of the app. Give a name to identify your SPA

    • Description: The description of the app.

  • Open the OAuth parameters section by clicking on the arrow.

  • Provide the following information
    • Token life time The life time of the issued token.

    • Redirection Uri: One or more redirection uri's. Only https is allowed. After the token is issued it will be passed as a parameter in the fragment of the redirection uri.

  • Click Save. You will navigate to the detail page of the just created App.


Step 2 - Add logic to signin.

Expand the Single Page App section, and copy the following information

  • Your ClientId
  • Your Redirection Uri
  • The authorization endpoint

In your SPA add a sign in button or link.

Bind a click event handler to the link and use the following code to form the url en redirect the browser.


    var url = [AUTHORIZATION_ENDPOINT] + "?response_type=token"
        + "&client_id=" + encodeURIComponent("[YOUR_CLIENT_ID]")
        + "&scope=" + encodeURIComponent("[ANY SCOPE]")
        + "&redirect_uri=" + encodeURIComponent("[YOUR_REDIRECT_URI]");
        + "&state=" + encodeURIComponent(window.location.pathname);

    window.location.href = url;

Step 3 - Add logic to retrieve the token.

Once a user clicks on the sign in link, the browser is redirected to the url you constructed above. After the user is authenticated the access token is returned using a redirect to the redirect uri you specified when registering your SPA.

Now we need to extract the access token from the uri fragment, by adding the following code to the page we registered as our redirect uri page.


    function getParameters() {
        var parameters = {};
        var queryString = location.hash.substring(1);
        var regex = /([^&=]+)=([^&]*)/g;
        var parameter;
        while (parameter = regex.exec(queryString)) {
            parameters[decodeURIComponent(parameter[1])] = decodeURIComponent(parameter[2]);
        }
        return parameters;
    };

    function parseResponse() {
        var parameters = getParameters();
        if (parameters) {
            if (parameters.error && parameters.error !== "") {
                // handle the error
            }
            else {
                var accessToken = parameters.access_token;
                if (accessToken && accessToken !== "") {
                    $.cookie("token", accessToken, { secure: true, path: '/' });
                }
            
                var state = parameters.state;
                if (state && state !== "") {
                        window.location.href = state;
                }
            }
        }
    }

When the page is loaded we call parseResponse to retrieve the access token and store it in a secure domain cookie. We use the state parameter to return the user to the initial page from where he clicked the sign in link.


Step 4 - Use the token to call an API.

When you want to call an API you need to provide the access token in the HTTP Authorization header.

If you are using the ajax functions of jQuery, this can easily be done by setting the header in the beforeSend callback. The following code demonstrates how to inject the access token in the header:


   function beforeSend(xhr, settings) {
        var accessToken = $.cookie("token");
        if (accessToken && accessToken !== "") {
            xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
        }
    };

    $.ajax("/{tenant}/api/identity/v1/friends", { 
        type: "GET",
        data: null,
        beforeSend: beforeSend 
    });


The beforeSend function will retrieve the access token we stored in the cookie and if an access token is available, it will set the HTTP Authorization header.

When invoking the ajax call, we set the beforeSend callback to the beforeSend function.