Wednesday, April 16, 2014

DurandalJs User Authentication

As you know for most business application user authentication is needed. These applications should allow only authenticated users to access them. With the trend towards building SPA application increasing, the need for user authentication in these SPA applications also increases. We need to authenticate users similar to what we were doing in the traditional web applications.

The user authentication in SPA applications poses us a challenge. As you know SPA applications runs on browser and makes REST requests to web server. Hence we need to authenticate user both in the SPA application and also in the web server. A note of caution is that user can manipulate javascript and can bypass your security in the SPA application, hence doing authentication and authorization on the server is a must.

In this blog I will talk on how to authenticate use in the SPA (DurandalJS) application. In the subsequent blog I will cover on how to authenticate on the server and ensure only authenticated users access the server resources.

Fortunately DurandalJS provides us all the necessary plumbing code. This is done through a method called guardRoute, which enables you to check whether user has permissions to access a route or a page.

router.guardRoute = function (instance, instruction) {
    //verify user authentication and authorization

From this guardRoute you can return a Boolean whether user is allowed or not, or a view that needs to be called if user is not allowed. You can even return a promise. Checkout the DurandalJS site for more information.

In my example I return a string (view) which needs to be called if user is not authorized. Here is my guardRoute  code

//setting up the guardRoute
router.guardRoute = function (instance, instruction) {
    if (session.isAutenticated() === false && instruction.config.route !== "login") {
        return 'login';

You need to have this code in shell.js.

As you see in the guardRoute I am checking user is authenticated or not and redirecting user to the login page. I am storing user authentication information in an object called session which is stored in the windows object.

In my login page, once user is authenticated on the server I set the isAuthenticated to true. Similar when user logs out, I set the isAuthenticated to false. guardRoute function takes care of everything else. Isn’t that neat. As you see DurandalJS makes user authentication very easy.

P.S. It seems that DurandalJS is not going to include Knockout in their subsequent releases. We need to wait and see what’s next there.


  1. Hi Prasanna,

    Nice article. What does your session object look like?

  2. Thanks for your feedback. I just blogged on using session object in my SPA.