Solved

ASP.net MVC4 Login Persist Problem

Posted on 2014-01-27
3
417 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Turn Insights Into Action

You’ve already invested in ITSM tools, chat applications, automation utilities, and more. Fortify these solutions with intelligent communications so you can drive business processes forward.

With xMatters, you'll never miss a beat.

Question has a verified solution.

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

What my article will show is if you ever had to do processing to a listbox without being able to just select all the items in it. My software Visual Studio 2008 crystal report v11 My issue was I wanted to add crystal report to a form and show…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
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…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

687 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