Search code examples
sessionasp.net-web-api2session-management

Form Authentication with WebAPI expires after 5 minutes


I have been creating a web project where I am using forms authentication using cookies to validate if the user is authentication.

Everything works fine, but when I host this on shared hosting, then the session expired after 5 minutes of inactivity. I have set the timeout in the config to 60 minutes.

<authentication mode="Forms">
            <forms name=".auth" protection="All" timeout="60"/>
        </authentication>

While Login, I have created a API called login where I am setting the authentication.

FormsAuthentication.SetAuthCookie(".auth", false);

And I check if the user is authenticated in the web API and my API looks like.

    [Authorize]
    [RoutePrefix("api/value")]
    public class ValueController : ApiController
    {
        // GET api/value
        [Route("get")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

    }

I do know that this is a very old/bad approach to validate through cookie but this is my legacy application and I can't change the authentication structure and use Owin.

Can anybody suggest why does it expires after 5 minutes of inactivity on shared hosting ? It does works properly on my local IIS and doesn't expires till 60 minutes.

Help is appriciated.


Solution

  • The reason is the hosting provider clears the session and the solution is to add the machineKey in web.config.

    <system.web>
        <machineKey decryption="AES" decryptionKey="ddE3434J4K3J3KLNDFPSODIFSFLKJW34L3OIUF" validation="HMACSHA256" validationKey="07dfdDUIEJSLDJFKLSJFEIOUR3989F8SDF90DF9D0F9DF9SD0F90SDF09SD0F9DF" />
    </system.web>
    

    (Please note this is a sample key. You have to generate a key and add to your config)