コード例 #1
0
        public CustomerModel Login(string userName, string password, bool createPersistentCookie = true)
        {
            var response = _customerRepository.Login(userName, password);
            var user     = response.Result;

            if (user == null)
            {
                return(null);
            }

            var now = DateTime.UtcNow.ToLocalTime();

            var sessionContext = DependencyResolver.Current.GetService <ISessionContext>();
            var sessionId      = sessionContext.SessionId;

            var session = new SessionUpdateModel()
            {
                CustomerId = user.UserId.ToString(),
                SessionId  = sessionId
            };

            _sessionRepository.UpdateUserSession(session);
            var ticket = new FormsAuthenticationTicket(
                1 /*version*/, user.UserId.ToString(),
                now,
                now.Add(_expirationTimeSpan),
                createPersistentCookie, user.UserId.ToString() + "~" + user.Username + "~" + sessionId.ToString(),
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                HttpOnly = true
            };

            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path   = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }

            //added the following line assuming that this will set IsAuthenticated=true
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
            //refer to teh following links, if the above does not works
            //http://stackoverflow.com/questions/1064271/asp-net-mvc-set-custom-iidentity-or-iprincipal
            //http://stackoverflow.com/questions/21679836/custom-identity-using-mvc5-and-owin
            //http://www.windowsdevcenter.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html

            _httpContext.Response.Cookies.Add(cookie);
            _cachedUser    = user;
            user.SessionId = sessionId.ToString();
            return(user);
        }