So there are lots of posts on StackOverflow regarding this, but I still was unable to solve my exact problem. Here’s the gist:
I have a website that requires authentication. I am using the standard .NET FormsAuthentication.SetAuthCookie() method to persist the user’s session.
My question is this: In the web.config file, there is a timeout attribute to the “/system.web/authentication/forms” node. If I set this value to say, 30 minutes, is this the time of user inactivity the user can have before their session expires?
The reason I ask is that no matter what I set this value to, if I set persistence to true in SetAuthCookie(), the expiration on the cookie set is 90 minutes. If I set persistence to false in SetAuthCookie(), the cookie expiration is set to “end of session”.
What is that “Timeout” attribute value actually setting, and how can I get a persistent cookie that lasts a month or a year or longer?
The parameter timeout you’ve found in
/system.web/authentication/formsis the timeout (in minutes) of the duration of authentication ticket.This means that after a certain amount of time of inactivity, a user is prompted to login again. If you try to check this
My.Profile.Current.IsAuthenticatedit will befalse.You can choose not to persist the cookie. In this situation if your ticket expires, your cookie expires too. The cookie (in case is persisted) has a purpose to remember the user if he/she comes back to your site.
You might want to persist your cookie for 10 years so the user will never have to insert username and password again, unless they’ve chosen to delete the cookie. The cookie is valid even if the browser is closed (when it is persisted).
Another important thing to remember is the parameter slidingExpiration:
if it’s true your authentication ticket will be renewed every time there’s activity on your site: refresh of the page etc.
What you can do – and what I’ve done – is to write your own cookie like this:
Update
I’ve implemented this routine cause I want to store my groups in an encrypted cookie:
As you can see I’ve set the expiration of the authentication cookie and the authentication ticket with the same timeout (only when persisted).
Another thing that I’ve tried is to stored username and password in the encrypted cookie.
Everytime a masterpage is loaded I check My.Profile.Current.IsAuthenticated to see if the authentication is still valid. If not I read the cookie again, get the username and password, and check it on the DB:
Security.CookieAuth is an object I’ve created to return username and password.
CookieUserData is the storage (I save in json format) where I put my password and groups.