public ValidateSessionResponse ValidateSession(ValidateSessionRequest request)
        {
            SessionToken session = SessionTokenManager.Instance.FindSession(request.SessionToken.Id);
            if (session!=null)
            {
                if (session.ExpiryTime < Platform.Time)
                {
                    Platform.Log(LogLevel.Error, "Session ID {0} already expired", session.Id);
                    SessionTokenManager.Instance.RemoveSession(request.SessionToken);
                    throw new FaultException<UserAccessDeniedException>(new UserAccessDeniedException());
                }

                if (!request.ValidateOnly)
                    session = SessionTokenManager.Instance.UpdateSession(session);

                if (Platform.IsLogLevelEnabled(LogLevel.Debug))
                    Platform.Log(LogLevel.Debug, "Session ID {0} is updated. Valid until {1}", session.Id, session.ExpiryTime);
                return new ValidateSessionResponse(session, Roles.GetRolesForUser(session.Id));
            }

#if false
            return new ValidateSessionResponse(new SessionToken(request.SessionToken.Id,DateTime.Now.AddHours(1)),
                new[] {AuthorityTokens.DataAccess.AllStudies,
                    AuthorityTokens.DataAccess.AllPartitions,
                    "Viewer/Visible",
                    "Viewer/Clinical"});
#endif

            Platform.Log(LogLevel.Error, "Session ID {0} does not exist", request.SessionToken.Id);
            throw new FaultException<UserAccessDeniedException>(new UserAccessDeniedException());
        }
        public ValidateSessionResponse ValidateSession(ValidateSessionRequest request)
        {
            SessionToken session = SessionTokenManager.Instance.FindSession(request.SessionToken.Id);
            if (session!=null)
            {
                if (session.ExpiryTime < Platform.Time)
                {
                    Platform.Log(LogLevel.Error, "Session ID {0} already expired", session.Id);
                    SessionTokenManager.Instance.RemoveSession(request.SessionToken);
                    throw new FaultException<UserAccessDeniedException>(new UserAccessDeniedException());
                }

                if (!request.ValidateOnly)
                    session = SessionTokenManager.Instance.UpdateSession(session);

                if (Platform.IsLogLevelEnabled(LogLevel.Debug))
                    Platform.Log(LogLevel.Debug, "Session ID {0} is updated. Valid until {1}", session.Id, session.ExpiryTime);

                var authority = Roles.GetRolesForUser(session.Id);
#if STANDALONE
                var list = new List<string>();
                list.AddRange(authority);
                list.Add(Enterprise.Authentication.AuthorityTokens.Study.ViewImages);
                list.Add("Viewer/Visible");
                list.Add("Viewer/Clinical");
                authority = list.ToArray();
#endif
                return new ValidateSessionResponse(session, authority, new Guid[0]);
            }

#if STANDALONE
            return new ValidateSessionResponse(new SessionToken(request.SessionToken.Id,DateTime.Now.AddHours(1)),
                new[] {AuthorityTokens.DataAccess.AllStudies,
                    AuthorityTokens.DataAccess.AllPartitions,
                    Enterprise.Authentication.AuthorityTokens.Study.ViewImages,
                    "Viewer/Visible",
                    "Viewer/Clinical"});
#else
            Platform.Log(LogLevel.Error, "Session ID {0} does not exist", request.SessionToken.Id);
            throw new FaultException<UserAccessDeniedException>(new UserAccessDeniedException());
#endif
        }
        public ValidateSessionResponse ValidateSession(ValidateSessionRequest request)
        {
            SessionToken session = SessionTokenManager.Instance.FindSession(request.SessionToken.Id);
            if (session!=null)
            {
                if (session.ExpiryTime < Platform.Time)
                {
                    Platform.Log(LogLevel.Error, "Session ID {0} already expired", session.Id);
                    throw new FaultException<UserAccessDeniedException>(new UserAccessDeniedException());
                }

                session = SessionTokenManager.Instance.UpdateSession(session);

                if (Platform.IsLogLevelEnabled(LogLevel.Debug))
                    Platform.Log(LogLevel.Debug, "Session ID {0} is updated. Valid until {1}", session.Id, session.ExpiryTime);
                return new ValidateSessionResponse(session, Roles.GetRolesForUser(session.Id));
            }
            Platform.Log(LogLevel.Error, "Session ID {0} does not exist", request.SessionToken.Id);
            throw new FaultException<UserAccessDeniedException>(new UserAccessDeniedException());
        }
		public ValidateSessionResponse ValidateSession(ValidateSessionRequest request)
		{
			Platform.CheckForNullReference(request, "request");
			Platform.CheckMemberIsSet(request.UserName, "UserName");
			Platform.CheckMemberIsSet(request.SessionToken, "SessionToken");

			// get the session
			var session = GetSession(request.SessionToken);
			if (session == null)
				throw new InvalidUserSessionException();

			// determine if still valid
			session.Validate(request.UserName, this.Settings.UserSessionTimeoutEnabled);

			// renew
			if (!request.ValidateOnly)
				session.Renew(GetSessionTimeout());

			// get authority tokens if requested
			var authorizations = request.GetAuthorizations ?
			                                               	PersistenceContext.GetBroker<IAuthorityTokenBroker>().FindTokensByUserName(request.UserName) : new string[0];

			// Get DataAccess authority groups if requested
			var groups = request.GetAuthorizations
			             	? PersistenceContext.GetBroker<IAuthorityGroupBroker>().FindDataGroupsByUserName(request.UserName)
			             	: new Guid[0];

			return new ValidateSessionResponse(session.GetToken(), authorizations, groups);
		}
		/// <summary>
		/// Verifies the specified session 
		/// </summary>
		/// <param name="userId"></param>
		/// <param name="sessionToken"></param>
		/// <param name="authorityTokens"></param>
		/// <param name="bypassCache">True to always bypass the response cache and get a "fresh" response from the server.</param>
		/// <returns></returns>
		public static bool VerifySession(string userId, string sessionToken, out string[] authorityTokens, bool bypassCache = false)
		{
			try
			{
				ValidateSessionResponse response = null;
				var request = new ValidateSessionRequest(userId, new SessionToken(sessionToken));
				if (bypassCache)
				{
					using (new ResponseCacheBypassScope())
					{
						Platform.GetService<IAuthenticationService>(service => response = service.ValidateSession(request));
					}
				}
				else
				{
					Platform.GetService<IAuthenticationService>(service => response = service.ValidateSession(request));
				}

				authorityTokens = response.AuthorityTokens;
				return response.SessionToken.ExpiryTime > Platform.Time; //TODO : Utc?
			}
			catch (FaultException<InvalidUserSessionException> e)
			{

			}

			authorityTokens = null;
			return false;
		}
Exemple #6
0
        private SessionInfo CheckSession(string tokenId, bool renew)
        {
            SessionInfo sessionInfo = SessionCache.Instance.Find(tokenId);
            if (sessionInfo == null)
            {
                throw new Exception(String.Format("Unexpected error: session {0} does not exist in the cache", tokenId));
            }

            var request = new ValidateSessionRequest(sessionInfo.Credentials.UserName,
                                                     sessionInfo.Credentials.SessionToken)
                              {
                                  GetAuthorizations = true,
                                  ValidateOnly = !renew
                              };
            try
            {
                SessionToken newToken = null;
                Platform.GetService(
                    delegate(IAuthenticationService service)
                        {
                            DateTime originalExpiryTime = sessionInfo.Credentials.SessionToken.ExpiryTime;
                            ValidateSessionResponse response = service.ValidateSession(request);

                            //If we're renewing, might as well renew well before expiry. If we're only validating,
                            //we don't want to force a call to the server unless it's actually expired.
                            var addSeconds = 0.0;
                            if (renew)
                            {
                                //Minor hack - the ImageServer client shows a little bar at the top of the page counting down to session timeout,
                                //and allowing the user to cancel. This timeout value determines when that bar shows up. If, however, the 
                                //validate response is being cached, we need to make sure we hit the server - otherwise the bar doesn't go away.
                                double.TryParse(ConfigurationManager.AppSettings.Get("ClientTimeoutWarningMinDuration"), out addSeconds);
                                addSeconds = Math.Max(addSeconds, 30);
                            }

                            if (Platform.Time.AddSeconds(addSeconds) >= response.SessionToken.ExpiryTime)
                            {
                                Platform.Log(LogLevel.Debug, "Session is at or near expiry; bypassing cache.");

                                //The response likely came from the cache, and we want to make sure we get a real validation response.
                                //Note that this only really matters when 2 processes are sharing a session, like ImageServer and Webstation.
                                using (new ResponseCacheBypassScope()) { response = service.ValidateSession(request); }
                            }

                            // update session info
                            string id = response.SessionToken.Id;
                            newToken = SessionCache.Instance.Renew(id, response.SessionToken.ExpiryTime);
                            sessionInfo.Credentials.Authorities = response.AuthorityTokens;
                            sessionInfo.Credentials.SessionToken = newToken;

                            if (Platform.IsLogLevelEnabled(LogLevel.Debug))
                            {
                                Platform.Log(LogLevel.Debug, "Session {0} for {1} is renewed. Valid until {2}", id, sessionInfo.Credentials.UserName, newToken.ExpiryTime);

                                if (originalExpiryTime == newToken.ExpiryTime)
                                {
                                    Platform.Log(LogLevel.Warn, "Session expiry time is not changed. Is it cached?");
                                }
                            }
                        });

                return sessionInfo;
            }
            catch(FaultException<InvalidUserSessionException> ex)
            {
                SessionCache.Instance.RemoveSession(tokenId);
                throw new SessionValidationException(ex.Detail);
            }
            catch(FaultException<UserAccessDeniedException> ex)
            {
                SessionCache.Instance.RemoveSession(tokenId);
                throw new SessionValidationException(ex.Detail);   
            }
            catch(Exception ex)
            {
                //TODO: for now we can't distinguish communicate errors and credential validation errors.
                // All exceptions are treated the same: we can't verify the login.
                var e = new SessionValidationException(ex);
                throw e;
            }            
        }
Exemple #7
0
        private SessionInfo CheckSession(string tokenId, bool renew)
        {
            SessionInfo sessionInfo = SessionCache.Instance.Find(tokenId);
            if (sessionInfo == null)
            {
                throw new Exception(String.Format("Unexpected error: session {0} does not exist in the cache", tokenId));
            }

            var request = new ValidateSessionRequest(sessionInfo.Credentials.UserName,
                                                     sessionInfo.Credentials.SessionToken)
                              {
                                  GetAuthorizations = true,
                                  ValidateOnly = !renew
                              };
            try
            {
                SessionToken newToken = null;
                Platform.GetService(
                    delegate(IAuthenticationService service)
                        {
                            DateTime originalExpiryTime = sessionInfo.Credentials.SessionToken.ExpiryTime;
                            ValidateSessionResponse response = service.ValidateSession(request);

                            //If we're renewing, might as well renew well before expiry. If we're only validating,
                            //we don't want to force a call to the server unless it's actually expired.
                            var addSeconds = renew ? 30 : 0;
                            if (Platform.Time.AddSeconds(addSeconds) >= response.SessionToken.ExpiryTime)
                            {
                                Platform.Log(LogLevel.Info, "Session is at or near expiry; bypassing cache.");

                                //The response likely came from the cache, and we want to make sure we get a real validation response.
                                //Note that this only really matters when 2 processes are sharing a session, like ImageServer and Webstation.
                                using (new ResponseCacheBypassScope()) { response = service.ValidateSession(request); }
                            }

                            // update session info
                            string id = response.SessionToken.Id;
                            newToken = SessionCache.Instance.Renew(id, response.SessionToken.ExpiryTime);
                            sessionInfo.Credentials.Authorities = response.AuthorityTokens;
                            sessionInfo.Credentials.SessionToken = newToken;

                            if (Platform.IsLogLevelEnabled(LogLevel.Debug))
                            {
                                Platform.Log(LogLevel.Debug, "Session {0} for {1} is renewed. Valid until {2}", id, sessionInfo.Credentials.UserName, newToken.ExpiryTime);

                                if (originalExpiryTime == newToken.ExpiryTime)
                                {
                                    Platform.Log(LogLevel.Warn, "Session expiry time is not changed. Is it cached?");
                                }
                            }
                        });

                return sessionInfo;
            }
            catch(FaultException<InvalidUserSessionException> ex)
            {
                SessionCache.Instance.RemoveSession(tokenId);
                throw new SessionValidationException(ex.Detail);
            }
            catch(FaultException<UserAccessDeniedException> ex)
            {
                SessionCache.Instance.RemoveSession(tokenId);
                throw new SessionValidationException(ex.Detail);   
            }
            catch(Exception ex)
            {
                //TODO: for now we can't distinguish communicate errors and credential validation errors.
                // All exceptions are treated the same: we can't verify the login.
                var e = new SessionValidationException(ex);
                throw e;
            }            
        }
Exemple #8
0
        public SessionToken Renew(string tokenId)
        {
            SessionInfo sessionInfo = SessionCache.Instance.Find(tokenId);
            if (sessionInfo == null)
            {
                throw new Exception(String.Format("Unexpected error: session {0} does not exist in the cache", tokenId));
            }

            var request = new ValidateSessionRequest(sessionInfo.Credentials.UserName,
                                                     sessionInfo.Credentials.SessionToken)
                              {
                                  GetAuthorizations = true
                              };

            try
            {
                SessionToken newToken = null;
                Platform.GetService(
                    delegate(IAuthenticationService service)
                        {
                            DateTime originalExpiryTime = sessionInfo.Credentials.SessionToken.ExpiryTime;
                            ValidateSessionResponse response = service.ValidateSession(request);
                            // update session info
                            string id = response.SessionToken.Id;
                            newToken= SessionCache.Instance.Renew(id, response.SessionToken.ExpiryTime);

                            if (Platform.IsLogLevelEnabled(LogLevel.Debug))
                            {
                                Platform.Log(LogLevel.Debug, "Session {0} for {1} is renewed. Valid until {2}", id, sessionInfo.Credentials.UserName, newToken.ExpiryTime);

                                if (originalExpiryTime == newToken.ExpiryTime)
                                {
                                    Platform.Log(LogLevel.Warn, "Session expiry time is not changed. Is it cached?");
                                }
                            }
                        });

                return newToken;
            }
            catch(FaultException<InvalidUserSessionException> ex)
            {
                throw new SessionValidationException(ex.Detail);
            }
            catch(FaultException<UserAccessDeniedException> ex)
            {
                throw new SessionValidationException(ex.Detail);   
            }
            catch(Exception ex)
            {
                //TODO: for now we can't distinguish communicate errors and credential validation errors.
                // All exceptions are treated the same: we can't verify the login.
                var e = new SessionValidationException(ex);
                throw e;
            }            
        }
        public SessionInfo VerifySession(string userId, string sessionTokenId)
        {
            SessionInfo sessionInfo = SessionCache.Instance.Find(sessionTokenId);
            if (sessionInfo != null) return sessionInfo;

            // Session does not exist in the cache.
            // Go to the server to see if the session exists
            // It may 
            var request = new ValidateSessionRequest(userId, new SessionToken(sessionTokenId))
            {
                GetAuthorizations = true,
                ValidateOnly = false // load the tokens too since we don't know anything about session yet
            };

            try
            {
                using (new ResponseCacheBypassScope()) //bypass the response cache
                {
                    Platform.GetService(
                    delegate(IAuthenticationService service)
                    {

                        ValidateSessionResponse response = service.ValidateSession(request);
                        sessionInfo = new SessionInfo(userId, userId, response.SessionToken);

                        SessionCache.Instance.AddSession(sessionTokenId, sessionInfo);
                        sessionInfo.Validate();

                    });

                }
                
                return sessionInfo;
            }
            catch (FaultException<InvalidUserSessionException> ex)
            {
                SessionCache.Instance.RemoveSession(sessionTokenId);
                throw new SessionValidationException(ex.Detail);
            }
            catch (FaultException<UserAccessDeniedException> ex)
            {
                SessionCache.Instance.RemoveSession(sessionTokenId);
                throw new SessionValidationException(ex.Detail);
            }
            catch (Exception ex)
            {
                //TODO: for now we can't distinguish communicate errors and credential validation errors.
                // All exceptions are treated the same: we can't verify the session.
                var e = new SessionValidationException(ex);
                throw e;
            }         
        }