Mar 29 2016

How to handle session expiry in Owin Authentication

Owin authentication makes use of token-based approach to implement authentication between the front-end application and the back-end API. We all know the common and conventional way to implement authentication is the cookie-based approach where the cookie is sent with each request from the client to the server and on the server it is used to identify the authenticated user.

Let's see how to start with Owin Authentication:

Create an empty solution and name it “AngularJSAuthentication”. Then add new ASP.NET Web application. Once you have done this, you have to install the NuGet packages which are needed to setup your Owin server.

Under Tools Menu, select NuGet Package Manager. From NuGet Package Manager menu select Package Manager Console and type:

Add a startup class:

Next, add an OWIN startup class. In Solution Explorer, right-click the project and select Add, then select New Item. In the Add New Item dialog, select Owin Startup class .

The OWIN Startup class template is available in Visual Studio.

Now the requirement is when the cookie is expired, I need to redirect to Login screen.

Having said that, I did face an issue here. I had set a time for the session to expire after some minutes of inactivity, but the session was not getting expired.

The following code was used.

The following code specifies the session expiry time:

Here the expiration time is set to 60000000000 nanoseconds.

But this code was not working, i.e., the session was not getting expired.

I updated the above code to:

Here the expiration time was set to 10 minutes, but still the session was not getting expired.

Even after setting the ExpireTimeSpan correctly the session was not getting expired. After debugging I found that the error was in web.config file:

This was changed to:

Once the remove name value was set to "FormsAuthentication" it started working.

Some of the benefits of using Owin are:

There is no dependency on shared session stores. The token sent to the server contains all the user information needed for authentication thus making the token self-contained. Adding more servers now becomes an easy task.

Your API is built in a way to understand this token and do the authentication, which means front-end application is not coupled with specific authentication mechanism. The token is generated from the server.

Loading Disqus Comments ...