Remember and automatically login a user in asp.net

Hi,

I like to implement a scenario where the code remembers and automatically logs in a returning user.
When the user register I want to save a cookie and then if the cookie exists and is valid automatically log in the user.

I know this can be done in asp.net and I have tried to start by doing this:

In web.config I set a cookie:
 <forms cookieless="UseCookies" defaultUrl="~/Default.aspx" domain="" enableCrossAppRedirects="false" loginUrl="~/Login" name=".ASPXAUTHPlay" path="/" protection="All" requireSSL="false" slidingExpiration="true" timeout="1440" />

Open in new window

Then I set this code when the user register:
FormsAuthentication.SetAuthCookie(txtUserName.Text, True)

Open in new window


But how can I now use the informataion in the created cookie (ASPXAUTHPlay) to log in the user automatically?

Thanks for help!
Peter NordbergIT ManagerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ambienceCommented:
I have this helper class that I use for
    public class CustomPrincipal : GenericPrincipal
    {
        public CustomPrincipal(IIdentity identity, string[] roles)
            : base(identity, roles)
        {
        }

        public int UserId { get; set; }
    }

Open in new window

    public class AuthenticationService
    {
        class AuthenticationToken
        {
            public int UserId { get; set; }
            public string[] Roles { get; set; }
        }

        public static bool IsAuthenticated()
        {
            return HttpContext.Current.Request.IsAuthenticated;
        }

        public static void SignInUser(string userName, bool rememberMe, int userId, string[] roles, int expirationDays = 3)
        {
            var userData = new JavaScriptSerializer().Serialize(new AuthenticationToken
                {
                    UserId = userId,
                    Roles = roles
                });
            var authTicket = new FormsAuthenticationTicket(
                     1,
                     userName,
                     DateTime.Now,
                     DateTime.Now.Add(TimeSpan.FromDays(expirationDays)),
                     rememberMe,
                     userData);

            var encTicket = FormsAuthentication.Encrypt(authTicket);
            var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            if (authTicket.IsPersistent)
                faCookie.Expires = authTicket.Expiration;
            HttpContext.Current.Response.Cookies.Add(faCookie);
        }

        public static void SignOffUser()
        {
            FormsAuthentication.SignOut();
        }

        public static void AuthenticateRequest()
        {
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                try
                {
                    var token = new JavaScriptSerializer().Deserialize<AuthenticationToken>(authTicket.UserData);
                    HttpContext.Current.User = new CustomPrincipal(new GenericIdentity(authTicket.Name), token.Roles)
                    {
                        UserId = token.UserId
                    };
                }
                catch (Exception)
                { 
                }
            }
        }
    }

Open in new window


Here is how I use it

    public class MvcApplication : HttpApplication
    {
        public MvcApplication()
        {
            this.PostAuthenticateRequest += delegate {
				AuthenticationService.AuthenticateRequest();
		};
        }

}

Open in new window


You should be able to adapt this code to your needs.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.