Solved

ASP.net MVC4 Login Persist Problem

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
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…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

820 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