Solved

ASP.net MVC4 Login Persist Problem

Posted on 2014-01-27
3
407 Views
Last Modified: 2014-02-16
Hi Experts,

I have an ASP.net MVC 4 project, and have succesfully implemented a forms authentication system, but cannot get the logins to persist (remember the user) for more than a few minutes. I have used a similar solution on an asp.net webforms sites and it works perfectly, with sliding expiration and remembers the user indefinatley until they log out.

Here is my web.config auth section:
 <authentication mode="Forms">
      <forms loginUrl="~/users/login/" defaultUrl="~/programs/admin/" name="CommConAuthCookie" timeout="20160" slidingExpiration="true" requireSSL="false" cookieless="AutoDetect"/>
    </authentication>

Open in new window


and here is my server side login code:
 <HttpPost()> _
        <AllowAnonymous> _
        Function Login(loginUser As SiteUser, Optional Persist As Boolean = False, Optional ReturnUrl As String = "~/programs/admin") As ActionResult
            Dim possibleUsers = (From s As SiteUser In db.SiteUsers Where s.UserEmail = loginUser.UserEmail)
            Dim siteuser As SiteUser
            If possibleUsers.Count <> 0 Then
                siteuser = possibleUsers.First
                Dim IsLoginValid As Boolean = siteuser.ValidateCredentials(loginUser.UserEmail, loginUser.Password)
                If IsLoginValid Then
                    Dim tkt As FormsAuthenticationTicket
                    Dim cookiestr As String
                    Dim ck As HttpCookie
                    tkt = New FormsAuthenticationTicket(1, siteuser.UserID, DateTime.Now(), Now.AddDays(30), Persist, "your custom data")
                    cookiestr = FormsAuthentication.Encrypt(tkt)
                    ck = New HttpCookie(FormsAuthentication.FormsCookieName(), cookiestr)
                    ck.Expires = tkt.Expiration
                    ck.Path = FormsAuthentication.FormsCookiePath()
                    Response.Cookies.Add(ck)
                    Dim aCookie As New HttpCookie("CommConUserCookie")
                    aCookie.Value = siteuser.UserID
                    aCookie.Expires = Now.AddDays(30)
                    Response.Cookies.Add(aCookie)
                    If String.IsNullOrEmpty(siteuser.TemporaryPassword) Then
                        Return Redirect(ReturnUrl)
                    Else
                        SetUserMessage("The password you have used is temporary, please change your password.")
                        Return Redirect("/users/changepassword/")
                    End If

                Else
                    ModelState.AddModelError("", "The username / password combination you entered is not valid.")
                    Return View()
                End If
            Else
                ModelState.AddModelError("", "The username / password combination you entered is not valid.")
                Return View()
            End If

        End Function

Open in new window


The server is hosted at GoDaddy, so I have very little control over the IIS, looking for a solution that doesn't require IIS access if possible.

Thanks! And Please let me know if you need any more information.
0
Comment
Question by:mylescardiff
  • 2
3 Comments
 
LVL 16

Expert Comment

by:Stephan
ID: 39814758
Is it only happening on your production environment or is it also locally? Maybe you are running on a load balanced environment (then you need to make sure you have specified the machineKey (validationKey and decryptionKey) for decryption)?

You can set the cookieless attribute to "UseDeviceProfile", on my opinion this is best.
More details here: http://msdn.microsoft.com/en-us/library/aa479315.aspx

The default way of creating an authentication cookie is by using the following method:

FormsAuthentication.SetAuthCookie(loginUser.UserEmail);

Open in new window


This cookie is used by the default FormsAuthentication framework and uses the settings specified in the configuration file.
0
 
LVL 1

Accepted Solution

by:
mylescardiff earned 0 total points
ID: 39851737
Sorry for the delay, just adding that line of code in addition to what i already had seems to have fixed the problem.

Thank you!
0
 
LVL 1

Author Closing Comment

by:mylescardiff
ID: 39862488
Forms.SetAuthCookie method was the trick to the application using the settings from web.config correctly.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now