• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 36
  • Last Modified:

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!
0
Peter Nordberg
Asked:
Peter Nordberg
1 Solution
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now