Solved

ASP.net MVC4 Login Persist Problem

Posted on 2014-01-27
3
412 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
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…

785 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