Beispiel #1
0
        public static void SignOut(ISecurityService authenticationService)
        {
            var cookie = AuthCookie.GetCurrent();

            if (cookie != null)
            {
                if (!string.IsNullOrEmpty(cookie.SessionUid))
                {
                    HttpContext.Current.Cache.Remove(cookie.SessionUid);
                    //ICacheService cacheService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve<ICacheService>();
                    //cacheService.Remove(string.Format("UserSessionID:{0}", cookie.SessionUid));
                    if (string.IsNullOrEmpty(cookie.Username))
                    {
                        authenticationService.SignOut(cookie.SessionUid);
                    }
                }

                cookie.SessionUid = null;
                cookie.Username   = null;
                cookie.UserRoles  = null;
                cookie.BranchCode = null;
                cookie.AuthExpiry = Helper.GetLocalDate().AddDays(-1);
                cookie.Delete();
            }

            //create a new anonymous identity/principal.
            var identity  = new System.Security.Principal.GenericIdentity("");
            var principal = new System.Security.Principal.GenericPrincipal(identity, null);

            //assign the anonymous principle to the context
            System.Web.HttpContext.Current.User      = principal;
            System.Threading.Thread.CurrentPrincipal = principal;
        }
Beispiel #2
0
        internal static bool IsSessionActive(string sessionId)
        {
            if (string.IsNullOrEmpty(sessionId))
            {
                return(false);
            }
            var settings = SecurityConfig.GetCurrent();
            var current  = AuthCookie.GetCurrent();
            ISecurityService authenticationService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve <ISecurityService>();
            var  userObject = authenticationService.GetUserBySessionId(sessionId);
            bool isActive   = false;

            if (userObject != null)
            {
                if ((!userObject.CurrentSessionId.HasValue || sessionId != userObject.CurrentSessionId.ToString()) ||
                    (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) > Helper.GetLocalDate()) ||
                    ((userObject.ApprovalStatus != Constants.ApprovalStatus.Approved) || userObject.IsLockedOut || userObject.IsDeleted))
                {
                    if (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) > Helper.GetLocalDate())
                    {
                        isActive = true;
                    }
                }
            }

            return(isActive);
        }
Beispiel #3
0
        private static void CreateThreadPrincipalAndAuthCookie(AuthenticationDataDto currentUser, SecurityConfig settings)
        {
            //create the cookie
            Identity  identity  = new Identity(new Guid(currentUser.SessionId), currentUser.Username, currentUser.Roles, currentUser.FullName, currentUser.BranchCode, currentUser.AccountType);
            Principal principal = new Principal(identity, identity.Roles, identity.AccountType);

            System.Web.HttpContext.Current.User      = principal;
            System.Threading.Thread.CurrentPrincipal = principal;

            var cookie = new AuthCookie();

            {
                cookie.SessionUid = currentUser.SessionId;
                if (settings.Cookie.CookieOnlyCheck)
                {
                    cookie.Username    = currentUser.Username;
                    cookie.UserRoles   = currentUser.Roles;
                    cookie.BranchCode  = currentUser.BranchCode;
                    cookie.AccountType = currentUser.AccountType;
                    cookie.AuthExpiry  = Helper.GetLocalDate().AddMinutes(settings.Cookie.Timeout);
                }
                cookie.Save();
            }

            if (!settings.Cookie.CookieOnlyCheck)
            {
                HttpContext.Current.Cache.Insert(currentUser.SessionId, currentUser, null, DateTime.UtcNow.AddSeconds(30), System.Web.Caching.Cache.NoSlidingExpiration);
            }
        }
Beispiel #4
0
        public static string CheckAccessByCookie()
        {
            var current        = AuthCookie.GetCurrent();
            var settings       = SecurityConfig.GetCurrent();
            var cookieNotFound = (current == null || current.SessionUid == null);

            AuthenticationDataDto dto = null;

            if (cookieNotFound || (settings.Cookie.CookieOnlyCheck && current.AuthExpiry < Helper.GetLocalDate()))
            {
                return(null);
            }
            else if (!settings.Cookie.CookieOnlyCheck)
            {
                dto = Access.Renew(current.SessionUid);
                if (dto == null)
                {
                    return(null);
                }
                else
                {
                    return(string.Format("{0}||{1}", dto.Username.Trim(), dto.Roles.Trim()));
                }
            }
            else if (settings.Cookie.CookieOnlyCheck)
            {
                return(string.Format("{0}||{1}", current.Username.Trim(), current.UserRoles.Trim()));
            }
            return(null);
        }
        // GET: Home
        public ActionResult Index()
        {
            AuthCookie _AuthCookie = new AuthCookie();



            return(View());
        }
Beispiel #6
0
        public static string GenerateAuthCookie(AuthContext authContext)
        {
            var hal = ComputeHal(authContext);

            if (hal.Length == 32)
            {
                hal = hal.Substring(0, 10) + authContext.Md5Password + hal.Substring(10);
            }

            var authCookie = new AuthCookie(authContext.User, hal, authContext.Nonce);

            return(JsonConvert.SerializeObject(authCookie));
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (!_authorizationStatus)
            {
                var settings  = SecurityConfig.GetCurrent();
                var current   = AuthCookie.GetCurrent();
                var sessionID = string.Empty;
                if (current != null)
                {
                    sessionID = current.SessionUid;
                    current.Delete();
                }

                string loginUrl = (settings.Login.Url + settings.Login.Page).ToLower();

                var rawUrl      = filterContext.HttpContext.Request.RawUrl;
                var redirectUrl = string.Empty;

                if (!string.IsNullOrEmpty(rawUrl) && rawUrl != loginUrl)
                {
                    if (!rawUrl.Contains("xxkeyxx")) //auto logout key
                    {
                        if (!Access.IsSessionActive(sessionID))
                        {
                            redirectUrl = "?ReturnUrl=" + HttpUtility.UrlEncode(rawUrl, filterContext.HttpContext.Request.ContentEncoding);
                        }
                        else
                        {
                            redirectUrl = string.Empty;
                        }

                        AddAlert(AlertStyles.Danger, "Your session has expired or you do not have access to the page you are trying to access.", true);
                    }
                    else
                    {
                        AddAlert(AlertStyles.Danger, string.Format("You have been logged out due to inactivity for {0} minutes. Please log in again.", SecurityConfig.GetCurrent().Cookie.Timeout), true);
                    }
                }

                if (!string.IsNullOrEmpty(sessionID))
                {
                    var context         = HttpContext.Current;
                    var securityService = ((IContainer)context.Application["container"]).Resolve <ISecurityService>();
                    securityService.SignOut(sessionID);
                }

                filterContext.Result = new RedirectResult(loginUrl + redirectUrl);
                return;
            }
        }
Beispiel #8
0
        private string CreateNonce(ClaimsPrincipal user, AuthCookie authCookie)
        {
            string action = "wp_rest"; // for our purposes it's always "wp-rest".
            var    id     = int.Parse(user.Claims.SingleOrDefault(x => x.Type == CLAIM_TYPE_ID).Value);

            // equivalent to wp_create_nonce: lines 2041-2052 in wp-includes/pluggable.php
            //var user = GetCurrentUser();
            var token = authCookie.Token;
            var i     = TickWordPressNone(); // wp_nonce_tick()

            string s      = $"{i}|{action}|{id}|{token}";
            var    hashed = WpHash(s, Scheme.NONCE);

            return(hashed.Substring(hashed.Length - 12, 10));
        }
Beispiel #9
0
        public void Remember(HttpResponseBase response, Author author)
        {
            foreach (var existingCookie in _dal.Query <AuthCookie>().Where(_ => _.Id == author.Id).ToList())
            {
                _dal.Delete(existingCookie);
            }
            var cookie = new AuthCookie
            {
                Author = author,
                Hash   = Guid.NewGuid()
            };

            _dal.Attach(cookie);
            response.SetCookie(new HttpCookie(AuthCookie, Convert.ToString(cookie.Hash)));
        }
Beispiel #10
0
        private static ISecurityService PerfomAccessCheck(HttpContextBase context)
        {
            var settings = SecurityConfig.GetCurrent();
            var current  = AuthCookie.GetCurrent();
            ISecurityService authenticationService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve <ISecurityService>();

            var cookieNotFound = (current == null || current.SessionUid == null);
            var cookiedDeleted = false;

            AuthenticationDataDto dto = null;

            if (cookieNotFound)
            {
                if (current != null)
                {
                    current.Delete();
                    cookiedDeleted = true;
                }
            }
            else if (settings.Cookie.CookieOnlyCheck && current.AuthExpiry < Helper.GetLocalDate())
            {
                current.Delete();
                cookiedDeleted = true;
            }
            else if (!settings.Cookie.CookieOnlyCheck)
            {
                dto = Access.Renew(current.SessionUid, authenticationService);
                if (dto == null)
                {
                    current.Delete();
                    cookiedDeleted = true;
                }
            }

            if (!cookiedDeleted)
            {
                if (dto == null)
                {
                    dto = new AuthenticationDataDto();
                }

                Identity identity = new Identity(new Guid(current.SessionUid),
                                                 settings.Cookie.CookieOnlyCheck ? current.Username : dto.Username,
                                                 settings.Cookie.CookieOnlyCheck ? current.UserRoles : dto.Roles, dto.FullName,
                                                 settings.Cookie.CookieOnlyCheck ? current.BranchCode : dto.BranchCode,
                                                 settings.Cookie.CookieOnlyCheck ? current.AccountType : dto.AccountType);
                var principal = new Principal(identity, identity.Roles, identity.AccountType);
                context.User            = principal;
                Thread.CurrentPrincipal = principal;

                if (settings.Cookie.SlidingExpiration && settings.Cookie.CookieOnlyCheck)
                {
                    current.AuthExpiry = Helper.GetLocalDate().AddMinutes(settings.Cookie.Timeout);
                    current.Save();
                }
            }

            var ip = context.Request.UserHostAddress;

            return(authenticationService);
        }
Beispiel #11
0
        public static AuthCookie Login()
        {
            string postData = "eblanguage=1&UserName=grombach&password=grombach123&button0=Anmelden&button0command=";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(postData);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://wega.mi-m.de/edms/exe/eb.exe?cfgs=../cfgs/Login.cfg&p=u2");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();

            HttpWebResponse loginResponse = (HttpWebResponse)request.GetResponse();
            string cookieData = loginResponse.Headers["Set-Cookie"];

            AuthCookie auth = new AuthCookie();
            auth.Parse(cookieData);
            return auth;
        }
Beispiel #12
0
        void DoCachedAuthentication(DotNetOpenAuth.OpenId.Provider.IAuthenticationRequest authRequest, ClaimsRequest claimsRequest, AuthCookie authCookie)
        {
            m_log.Info("[CABLE BEACH IDP]: Using cached login credentials for " + authCookie.UserProfile.Name);

            authRequest.ClaimedIdentifier = authCookie.Identity;
            authRequest.IsAuthenticated = true;

            if (claimsRequest != null)
            {
                // Fill in a few Simple Registration values if there was a request for SREG data
                ClaimsResponse claimsResponse = claimsRequest.CreateResponse();
                claimsResponse.Email = authCookie.UserProfile.Email;
                claimsResponse.FullName = authCookie.UserProfile.Name;
                claimsResponse.BirthDate = Utils.UnixTimeToDateTime(authCookie.UserProfile.Created);
                authRequest.AddResponseExtension(claimsResponse);

                m_log.Debug("[CABLE BEACH IDP]: Appended SREG values to the positive assertion response");
            }
        }