def testAuthenticationProcessingFilterWithBadPassword(self):
        def start_response():
            pass
        def application(environ, start_response):
            return ["Success"]

        environ = {}
        environ["PATH_INFO"] = "/index.html"
        
        inMemoryUserDetailsService = InMemoryUserDetailsService()
        inMemoryUserDetailsService.user_dict = {"user1": ("good_password", ["role1", "blue"], True)}
        inMemoryDaoAuthenticationProvider = DaoAuthenticationProvider()
        inMemoryDaoAuthenticationProvider.user_details_service = inMemoryUserDetailsService
        inMemoryDaoAuthenticationManager = AuthenticationManager([inMemoryDaoAuthenticationProvider])

        authenticationFilter = AuthenticationProcessingFilter()
        authenticationFilter.auth_manager = inMemoryDaoAuthenticationManager
        authenticationFilter.alwaysReauthenticate = False
        
        token = UsernamePasswordAuthenticationToken("user1", "bad_password", None)
        self.assertFalse(token.isAuthenticated())
        
        SecurityContextHolder.setContext(SecurityContext())
        SecurityContextHolder.getContext().authentication = token
        
        filterChainProxy = FilterChainProxy()
        filterChainProxy.filterInvocationDefinitionSource = [("/.*", [authenticationFilter])]
        filterChainProxy.application = application
        self.assertRaises(BadCredentialsException, filterChainProxy, environ, start_response)
        self.assertFalse(SecurityContextHolder.getContext().authentication.isAuthenticated())
Esempio n. 2
0
    def __call__(self, environ, start_response):
        """
        Check if the user is trying to access the login url. Then see if they are already authenticated (and
        alwaysReauthenticate is disabled). Finally, try to authenticate the user. If successful, stored credentials
        in SecurityContextHolder. Otherwise, redirect to the login page.
        """
        # If the user is already authenticated, skip this filter.
        if not self.alwaysReauthenticate and SecurityContextHolder.getContext(
        ).authentication.isAuthenticated():
            self.logger.debug(
                "You are not required to reauthenticate everytime, and appear to already be authenticted, access GRANTED."
            )
            return self.doNextFilter(environ, start_response)

        try:
            # Authenticate existing credentials using the authentication manager.
            token = SecurityContextHolder.getContext().authentication
            self.logger.debug(
                "Trying to authenticate %s using the authentication manager" %
                token)
            SecurityContextHolder.getContext(
            ).authentication = self.auth_manager.authenticate(token)
            self.logger.debug(
                "%s was successfully authenticated, access GRANTED." %
                token.username)
        except AuthenticationException, e:
            self.logger.debug("Authentication failure, access DENIED.")
            raise
Esempio n. 3
0
    def attemptAuthentication(self, username, password):
        """Authenticate a new username/password pair using the authentication manager."""
        self.logger.debug("Trying to authenticate %s using the authentication manager" % username)
        token = UsernamePasswordAuthenticationToken(username, password)
        SecurityContextHolder.getContext().authentication = self.authenticationManager.authenticate(token)
	self.httpContextFilter.saveContext()
        self.logger.debug(SecurityContextHolder.getContext())
Esempio n. 4
0
 def attemptAuthentication(self, username, password):
     """Authenticate a new username/password pair using the authentication manager."""
     self.logger.debug("Trying to authenticate %s using the authentication manager" % username)
     token = UsernamePasswordAuthenticationToken(username, password)
     SecurityContextHolder.getContext().authentication = self.authenticationManager.authenticate(token)
     self.httpContextFilter.saveContext()
     self.logger.debug(SecurityContextHolder.getContext())
Esempio n. 5
0
 def before_invocation(self, invocation):
     attr = self.obtain_obj_def_source().get_attributes(invocation)
     if attr:
         self.logger.debug("Secure object: %s; ConfigAttributes: %s" %
                           (invocation, attr))
         if not SecurityContextHolder.getContext().authentication:
             raise AuthenticationCredentialsNotFoundException(
                 "An Authentication object was not found in the security credentials"
             )
         if not SecurityContextHolder.getContext(
         ).authentication.isAuthenticated():
             authenticated = self.auth_manager.authenticate(
                 SecurityContextHolder.getContext().authentication)
             self.logger.debug("Successfully Authenticated: " +
                               authenticated)
             SecurityContextHolder.getContext(
             ).authentication = authenticated
         else:
             authenticated = SecurityContextHolder.getContext(
             ).authentication
             self.logger.debug("Previously Authenticated: %s" %
                               authenticated)
         self.access_decision_mgr.decide(authenticated, invocation, attr)
         self.logger.debug("Authorization successful")
         return InterceptorStatusToken(authenticated, attr, invocation)
     else:
         return None
Esempio n. 6
0
 def run(self):
     context = cherrypy.session.get("SPRINGPYTHON_SECURITY_CONTEXT_KEY")
     if not context:
         context = self.newContext()
     
     SecurityContextHolder.setContext(context)
     cherrypy.session["SPRINGPYTHON_SECURITY_CONTEXT_KEY"] = context
Esempio n. 7
0
 def attemptAuthentication(self, username, password):
     """Authenticate a new username/password pair using the authentication manager."""
     token = UsernamePasswordAuthenticationToken(username, password)
     self.logger.debug("Trying to authenticate '%s' using the authentication manager: %s" % (username, token))
     x = self.authenticationManager.authenticate(token)
     SecurityContextHolder.getContext().authentication = x
     self.logger.debug(SecurityContextHolder.getContext())
     return x
 def setupContext(self, username, password):
     applicationContext = ApplicationContext(XMLConfig("support/unanimousBasedApplicationContext.xml"))
     token = UsernamePasswordAuthenticationToken(username, password)
     auth_manager = applicationContext.get_object("auth_manager")
     SecurityContextHolder.setContext(SecurityContext())
     SecurityContextHolder.getContext().authentication = auth_manager.authenticate(token)
     self.sampleService = applicationContext.get_object("sampleService")
     self.block1 = SampleBlockOfData("block1")
     self.block2 = SampleBlockOfData("block2")
 def setupContext(self, username, password):
     applicationContext = ApplicationContext(XMLConfig("support/labelBasedAclVoterApplicationContext.xml"))
     token = UsernamePasswordAuthenticationToken(username, password)
     auth_manager = applicationContext.get_object("auth_manager")
     SecurityContextHolder.setContext(SecurityContext())
     SecurityContextHolder.getContext().authentication = auth_manager.authenticate(token)
     self.sampleService = applicationContext.get_object("sampleService")
     self.blueblock = SampleBlockOfData("blue")
     self.orangeblock = SampleBlockOfData("orange")
     self.sharedblock = SampleBlockOfData("blue-orange")
    def testIoCDaoAuthenticationGoodUser1(self):
        self.mock.expects(once()).method("execute").id("#1")
        self.mock.expects(once()).method("fetchall").will(return_value([('user1', 'password1', True)])).id("#2").after("#1")
        self.mock.expects(once()).method("execute").id("#3").after("#2")
        self.mock.expects(once()).method("fetchall").will(return_value([('user1', 'role1'), ('user1', 'blue')])).id("#4").after("#3")

        authentication = UsernamePasswordAuthenticationToken(username="******", password="******")
        SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
        
        self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths)
        self.assertTrue("blue" in SecurityContextHolder.getContext().authentication.granted_auths)
Esempio n. 11
0
 def setupContext(self, username, password):
     applicationContext = ApplicationContext(
         XMLConfig("support/unanimousBasedApplicationContext.xml"))
     token = UsernamePasswordAuthenticationToken(username, password)
     auth_manager = applicationContext.get_object("auth_manager")
     SecurityContextHolder.setContext(SecurityContext())
     SecurityContextHolder.getContext(
     ).authentication = auth_manager.authenticate(token)
     self.sampleService = applicationContext.get_object("sampleService")
     self.block1 = SampleBlockOfData("block1")
     self.block2 = SampleBlockOfData("block2")
Esempio n. 12
0
 def run(self):
     if SecurityContextHolder.getContext().authentication.isAuthenticated():
         cherrypy.log("You are not required to reauthenticate everytime, and appear to already be authenticted, access GRANTED.")
     
     try:
         token = SecurityContextHolder.getContext().authentication
         cherrypy.log("Trying to authenticate %s using the authentication manager" % token)
         SecurityContextHolder.getContext().authentication = self.authManager.authenticate(token)
         cherrypy.log("%s was successfully authenticated, access GRANTED." % token.username)
     except AuthenticationException, e:
         cherrypy.log("Authentication failure, access DENIED.")
         raise cherrypy.HTTPRedirect(self.redirectPath)
Esempio n. 13
0
 def session_start_response(status, headers, exc_info = None):
     session[self.SPRINGPYTHON_SECURITY_CONTEXT_KEY] = \
         pickle.dumps(SecurityContextHolder.getContext())
     SecurityContextHolder.clearContext()
     self.logger.debug("SecurityContextHolder cleared out, as request processing completed")
     if session.accessed():
         session.persist()
         if session.__dict__['_headers']['set_cookie']:
             cookie = session.__dict__['_headers']['cookie_out']
             if cookie:
                 headers.append(('Set-cookie', cookie))
     return start_response(status, headers, exc_info)
Esempio n. 14
0
 def setupContext(self, username, password):
     applicationContext = ApplicationContext(
         XMLConfig("support/labelBasedAclVoterApplicationContext.xml"))
     token = UsernamePasswordAuthenticationToken(username, password)
     auth_manager = applicationContext.get_object("auth_manager")
     SecurityContextHolder.setContext(SecurityContext())
     SecurityContextHolder.getContext(
     ).authentication = auth_manager.authenticate(token)
     self.sampleService = applicationContext.get_object("sampleService")
     self.blueblock = SampleBlockOfData("blue")
     self.orangeblock = SampleBlockOfData("orange")
     self.sharedblock = SampleBlockOfData("blue-orange")
Esempio n. 15
0
    def testAuthenticationProcessingFilterWithGoodPassword(self):
        def start_response():
            pass

        def application(environ, start_response):
            return ["Success"]

        environ = {}
        environ["PATH_INFO"] = "/index.html"

        inMemoryUserDetailsService = InMemoryUserDetailsService()
        inMemoryUserDetailsService.user_dict = {
            "user1": ("good_password", ["role1", "blue"], True)
        }
        inMemoryDaoAuthenticationProvider = DaoAuthenticationProvider()
        inMemoryDaoAuthenticationProvider.user_details_service = inMemoryUserDetailsService
        inMemoryDaoAuthenticationManager = AuthenticationManager(
            [inMemoryDaoAuthenticationProvider])

        authenticationFilter = AuthenticationProcessingFilter()
        authenticationFilter.auth_manager = inMemoryDaoAuthenticationManager
        authenticationFilter.alwaysReauthenticate = False

        token = UsernamePasswordAuthenticationToken("user1", "good_password",
                                                    None)
        self.assertFalse(token.isAuthenticated())

        SecurityContextHolder.setContext(SecurityContext())
        SecurityContextHolder.getContext().authentication = token

        filterChainProxy = FilterChainProxy()
        filterChainProxy.filterInvocationDefinitionSource = [
            ("/.*", [authenticationFilter])
        ]
        filterChainProxy.application = application

        self.assertEquals(["Success"],
                          filterChainProxy(environ, start_response))
        self.assertTrue(SecurityContextHolder.getContext().authentication.
                        isAuthenticated())

        self.assertEquals(["Success"],
                          filterChainProxy(environ, start_response))
        self.assertTrue(SecurityContextHolder.getContext().authentication.
                        isAuthenticated())
Esempio n. 16
0
 def before_invocation(self, invocation):
     attr = self.obtain_obj_def_source().get_attributes(invocation)
     if attr:
         self.logger.debug("Secure object: %s; ConfigAttributes: %s" % (invocation, attr))
         if not SecurityContextHolder.getContext().authentication:
             raise AuthenticationCredentialsNotFoundException("An Authentication object was not found in the security credentials")
         if not SecurityContextHolder.getContext().authentication.isAuthenticated():
             authenticated = self.auth_manager.authenticate(SecurityContextHolder.getContext().authentication)
             self.logger.debug("Successfully Authenticated: " + authenticated)
             SecurityContextHolder.getContext().authentication = authenticated
         else:
             authenticated = SecurityContextHolder.getContext().authentication
             self.logger.debug("Previously Authenticated: %s" % authenticated)
         self.access_decision_mgr.decide(authenticated, invocation, attr)
         self.logger.debug("Authorization successful")
         return InterceptorStatusToken(authenticated, attr, invocation)
     else:
         return None
Esempio n. 17
0
 def __init__(self, context_config_files):
     """ """
     self.logger = logging.getLogger("seminode.core.runtime.wsgi.WSGIRuntime")
     context_config = []
     if not isinstance(context_config_files, list):
         context_config_files = [context_config_files]
     for cfg in context_config_files:
         file_ext = path.splitext(cfg)[1]
         file_ext = file_ext.strip(".")
         self.logger.debug(file_ext)
         reader = self.config_reader_map.get(file_ext, None)
         if not reader:
             raise SeminodeConfigurationError("No reader found for: %s" % cfg)
         context_config.append(reader(cfg))
     application_context = ApplicationContext(context_config)
     SecurityContextHolder.setStrategy(SecurityContextHolder.MODE_THREADLOCAL)
     SecurityContextHolder.getContext()
     self.wsgi_app = application_context.get_object("filterchain.proxy")
    def testIoCDaoAuthenticationGoodUsers(self):                
        authentication = UsernamePasswordAuthenticationToken(username="******", password="******")
        SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
        self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths)
        self.assertTrue("blue" in SecurityContextHolder.getContext().authentication.granted_auths)
        
        authentication = UsernamePasswordAuthenticationToken(username="******", password="******")
        SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
        self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths)
        self.assertTrue("orange" in SecurityContextHolder.getContext().authentication.granted_auths)

        authentication = UsernamePasswordAuthenticationToken(username="******", password="******")
        SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
        self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths)
        self.assertTrue("admin" in SecurityContextHolder.getContext().authentication.granted_auths)
Esempio n. 19
0
 def run(self):
     try:
         username = cherrypy.request.params.get('username', '')
         password = cherrypy.request.params.get('password', '')
         token = UsernamePasswordAuthenticationToken(username, password)
         SecurityContextHolder.getContext().authentication = self.authManager.authenticate(token)
         cherrypy.log("%s was successfully authenticated, access GRANTED." % token.username)
     except AuthenticationException, e:
         cherrypy.log("Authentication failure, access DENIED.")
         raise cherrypy.HTTPRedirect('/')
Esempio n. 20
0
 def __call__(self, environ, start_response):
     """
     Check if the user is trying to access the login url. Then see if they are already authenticated (and
     alwaysReauthenticate is disabled). Finally, try to authenticate the user. If successful, stored credentials
     in SecurityContextHolder. Otherwise, redirect to the login page.
     """
     # If the user is already authenticated, skip this filter.
     if not self.alwaysReauthenticate and SecurityContextHolder.getContext().authentication.isAuthenticated():
         self.logger.debug("You are not required to reauthenticate everytime, and appear to already be authenticted, access GRANTED.")
         return self.doNextFilter(environ, start_response)
     
     try:
         # Authenticate existing credentials using the authentication manager.
         token = SecurityContextHolder.getContext().authentication
         self.logger.debug("Trying to authenticate %s using the authentication manager" % token)
         SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(token)
         self.logger.debug("%s was successfully authenticated, access GRANTED." % token.username)
     except AuthenticationException, e:
         self.logger.debug("Authentication failure, access DENIED.")
         raise
Esempio n. 21
0
 def new_message(self, message="This is a sample twitter message."):
     """Send a new message"""
     message = (
         message,
         SecurityContextHolder.getContext().authentication.username,
         time.strftime(self.time_format, time.gmtime()),
     )
     # message = (message, "jcoleman", time.strftime(self.time_format, time.gmtime()))
     pickled_message = pickle.dumps(message)
     try:
         self.poller.send_message(pickled_message)
     except Exception, e:
         self.logger.error(e)
         raise self.redirectStrategy.redirect("/?notice=%s" % urllib.quote("Failed to send message"))
Esempio n. 22
0
 def __call__(self, environ, start_response):
     session = SessionObject(environ, **self.options)
     environ[self.environ_key] = session
     
     # SpringPython Security Context Initialization
     if session:
         context_from_session_object = None
         if self.SPRINGPYTHON_SECURITY_CONTEXT_KEY in session:
             context_from_session_object = pickle.loads(
                 session[self.SPRINGPYTHON_SECURITY_CONTEXT_KEY]
             )
         if context_from_session_object:
             if isinstance(context_from_session_object, SecurityContext):
                 self.logger.debug("Obtained from SPRINGPYTHON_SECURITY_CONTEXT_KEY a \
                         valid SecurityContext and set to \
                         SecurityContextHolder: '%s'" % context_from_session_object)
                 SecurityContextHolder.setContext(context_from_session_object)
             else:
                 self.logger.warn("SPRINGPYTHON_SECURITY_CONTEXT_KEY did not contain a SecurityContext but contained: '%s'" % context_from_session_object
                                     + "'; are you improperly modifying the HttpSession directly (you should always use " 
                                     + "SecurityContextHolder) or using the HttpSession attribute reserved for this class? "
                                     + "- new SecurityContext instance associated  with SecurityContextHolder")
                 SecurityContextHolder.setContext(self.generate_new_context())
         else:
             self.logger.debug("HttpSession returned null object for SPRINGPYTHON_SECURITY_CONTEXT_KEY " +
                                 "- new SecurityContext instance associated with SecurityContextHolder")
             SecurityContextHolder.setContext(self.generate_new_context())
             
     else:
         self.logger.debug("No HttpSession currently exists - new SecurityContext instance associated with SecurityContextHolder")
         SecurityContextHolder.setContext(self.generate_new_context())
     
     def session_start_response(status, headers, exc_info = None):
         session[self.SPRINGPYTHON_SECURITY_CONTEXT_KEY] = \
             pickle.dumps(SecurityContextHolder.getContext())
         SecurityContextHolder.clearContext()
         self.logger.debug("SecurityContextHolder cleared out, as request processing completed")
         if session.accessed():
             session.persist()
             if session.__dict__['_headers']['set_cookie']:
                 cookie = session.__dict__['_headers']['cookie_out']
                 if cookie:
                     headers.append(('Set-cookie', cookie))
         return start_response(status, headers, exc_info)
     
     return self.doNextFilter(environ, session_start_response)
Esempio n. 23
0
 def logout(self):
     SecurityContextHolder.getContext().authentication = UsernamePasswordAuthenticationToken()
Esempio n. 24
0
 def logout(self):
     SecurityContextHolder.getContext(
     ).authentication = UsernamePasswordAuthenticationToken()
 def setUp(self):
     SecurityContextHolder.setContext(SecurityContext())
     self.appContext = ApplicationContext(XMLConfig("support/providerApplicationContext.xml"))
     self.auth_manager = self.appContext.get_object("dao_mgr_hiding_exception")
     self.mock = self.mock()
     self.appContext.get_object("dataSource").stubConnection.mockCursor = self.mock
Esempio n. 26
0
 def setUp(self):
     SecurityContextHolder.setContext(SecurityContext())
     self.appContext = ApplicationContext(XMLConfig("support/ldapApplicationContext.xml"))
Esempio n. 27
0
    # while executing the sample application.

    logger = logging.getLogger("springpython")
    loggingLevel = logging.DEBUG
    logger.setLevel(loggingLevel)
    ch = logging.StreamHandler()
    ch.setLevel(loggingLevel)
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    applicationContext = ApplicationContext(noxml.PetClinicClientOnly())
    applicationContext.get_object("filterChainProxy")

    SecurityContextHolder.setStrategy(SecurityContextHolder.MODE_GLOBAL)
    SecurityContextHolder.getContext()

    conf = {
        '/': {
            "tools.staticdir.root": os.getcwd(),
            "tools.sessions.on": True,
            "tools.filterChainProxy.on": True
        },
        "/images": {
            "tools.staticdir.on": True,
            "tools.staticdir.dir": "images"
        },
        "/html": {
            "tools.staticdir.on": True,
            "tools.staticdir.dir": "html"
Esempio n. 28
0
 def doSomethingOnThis(self, block1, block2):
     self.logger.debug("You made it! Your context is %s" %
                       SecurityContextHolder.getContext().authentication)
     return "You made it!"
Esempio n. 29
0
    logger = logging.getLogger("springpython")
    loggingLevel = logging.DEBUG
    logger.setLevel(loggingLevel)
    ch = logging.StreamHandler()
    ch.setLevel(loggingLevel)
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") 
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    
    # This sample loads the IoC container from an XML file. The XML-based application context
    # automatically resolves all dependencies and order of instantiation for you. 

    applicationContext = ApplicationContext(XMLConfig(config_location = "applicationContext.xml"))
    applicationContext.get_object("filterChainProxy")

    SecurityContextHolder.setStrategy(SecurityContextHolder.MODE_GLOBAL)
    SecurityContextHolder.getContext()
    
    conf = {'/': 	{"tools.staticdir.root": os.getcwd(),
                         "tools.sessions.on": True,
                         "tools.filterChainProxy.on": True},
            "/images": 	{"tools.staticdir.on": True,
                         "tools.staticdir.dir": "images"},
            "/html": 	{"tools.staticdir.on": True,
                      	 "tools.staticdir.dir": "html"}
            }

    form = applicationContext.get_object(name = "root")
    form.filter = applicationContext.get_object(name = "authenticationProcessingFilter")
    form.hashedUserDetailsServiceList = [applicationContext.get_object(name = "md5UserDetailsService"),
                                         applicationContext.get_object(name = "shaUserDetailsService")]
Esempio n. 30
0
    def testGoodUserWithShaEncoding(self):
        self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2")

        authentication = UsernamePasswordAuthenticationToken(username="******", password="******")
        SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
        self.assertTrue("ROLE_DEVELOPERS" in SecurityContextHolder.getContext().authentication.granted_auths)
Esempio n. 31
0
 def saveContext(self):
     self.sessionStrategy.setHttpSession(self.SPRINGPYTHON_SECURITY_CONTEXT_KEY,
                                         pickle.dumps(SecurityContextHolder.getContext()))
Esempio n. 32
0
    def __call__(self, environ, start_response):
        """This filter copies SecurityContext information back and forth between the HttpSession and the SecurityContextHolder."""

        httpSession = self.sessionStrategy.getHttpSession(environ)
        contextWhenChainProceeded = None

        if httpSession is not None:

            contextFromSessionObject = None
            if self.SPRINGPYTHON_SECURITY_CONTEXT_KEY in httpSession:
                contextFromSessionObject = pickle.loads(
                    httpSession[self.SPRINGPYTHON_SECURITY_CONTEXT_KEY])

            if contextFromSessionObject is not None:
                if isinstance(contextFromSessionObject, SecurityContext):
                    self.logger.debug(
                        "Obtained from SPRINGPYTHON_SECURITY_CONTEXT_KEY a valid SecurityContext and set "
                        + "to SecurityContextHolder: '%s'" %
                        contextFromSessionObject)
                    SecurityContextHolder.setContext(contextFromSessionObject)
                else:
                    self.logger.warn(
                        "SPRINGPYTHON_SECURITY_CONTEXT_KEY did not contain a SecurityContext but contained: '%s'"
                        % contextFromSessionObject +
                        "'; are you improperly modifying the HttpSession directly (you should always use "
                        +
                        "SecurityContextHolder) or using the HttpSession attribute reserved for this class? "
                        +
                        "- new SecurityContext instance associated  with SecurityContextHolder"
                    )
                    SecurityContextHolder.setContext(self.generateNewContext())
            else:
                self.logger.debug(
                    "HttpSession returned null object for SPRINGPYTHON_SECURITY_CONTEXT_KEY "
                    +
                    "- new SecurityContext instance associated with SecurityContextHolder"
                )
                SecurityContextHolder.setContext(self.generateNewContext())

        else:
            self.logger.debug(
                "No HttpSession currently exists - new SecurityContext instance associated with SecurityContextHolder"
            )
            SecurityContextHolder.setContext(self.generateNewContext())

        self.logger.debug("Setting contextWhenChainProceeded to %s" %
                          SecurityContextHolder.getContext())
        contextWhenChainProceeded = str(SecurityContextHolder.getContext())

        results = self.doNextFilter(environ, start_response)

        self.sessionStrategy.setHttpSession(
            self.SPRINGPYTHON_SECURITY_CONTEXT_KEY,
            pickle.dumps(SecurityContextHolder.getContext()))
        self.logger.debug("SecurityContext stored to HttpSession: '%s'" %
                          SecurityContextHolder.getContext())

        SecurityContextHolder.clearContext()
        self.logger.debug(
            "SecurityContextHolder cleared out, as request processing completed"
        )

        return results
 def setUp(self):
     SecurityContextHolder.setContext(SecurityContext())
     self.appContext = ApplicationContext(XMLConfig("support/providerApplicationContext.xml"))
     self.auth_manager = self.appContext.get_object("inMemoryDaoAuthenticationManager")
Esempio n. 34
0
 def saveContext(self):
     self.sessionStrategy.setHttpSession(
         self.SPRINGPYTHON_SECURITY_CONTEXT_KEY,
         pickle.dumps(SecurityContextHolder.getContext()))
Esempio n. 35
0
 def __call__(self, environ, start_response):
     if not SecurityContextHolder.getContext(
     ).authentication.isAuthenticated():
         SecurityContextHolder.getContext().authentication.setAuthenticated(
             True)
     return self.doNextFilter(environ, start_response)
 def __call__(self, environ, start_response):
     if not SecurityContextHolder.getContext().authentication.isAuthenticated():
         SecurityContextHolder.getContext().authentication.setAuthenticated(True)
     return self.doNextFilter(environ, start_response)
 def doSomethingOnThis(self, block1, block2):
     self.logger.debug("You made it! Your context is %s" % SecurityContextHolder.getContext().authentication)
     return "You made it!"
Esempio n. 38
0
    def __call__(self, environ, start_response):
        """This filter copies SecurityContext information back and forth between the HttpSession and the SecurityContextHolder."""

        httpSession = self.sessionStrategy.getHttpSession(environ)
        contextWhenChainProceeded = None
        
        if httpSession is not None:

            contextFromSessionObject = None
            if self.SPRINGPYTHON_SECURITY_CONTEXT_KEY in httpSession:
                contextFromSessionObject = pickle.loads(httpSession[self.SPRINGPYTHON_SECURITY_CONTEXT_KEY])
            
            if contextFromSessionObject is not None:
                if isinstance(contextFromSessionObject, SecurityContext):
                    self.logger.debug("Obtained from SPRINGPYTHON_SECURITY_CONTEXT_KEY a valid SecurityContext and set "
                                        + "to SecurityContextHolder: '%s'" % contextFromSessionObject)
                    SecurityContextHolder.setContext(contextFromSessionObject)
                else:
                    self.logger.warn("SPRINGPYTHON_SECURITY_CONTEXT_KEY did not contain a SecurityContext but contained: '%s'" % contextFromSessionObject
                                        + "'; are you improperly modifying the HttpSession directly (you should always use " 
                                        + "SecurityContextHolder) or using the HttpSession attribute reserved for this class? "
                                        + "- new SecurityContext instance associated  with SecurityContextHolder")
                    SecurityContextHolder.setContext(self.generateNewContext())
            else:
                self.logger.debug("HttpSession returned null object for SPRINGPYTHON_SECURITY_CONTEXT_KEY " + 
                                    "- new SecurityContext instance associated with SecurityContextHolder")
                SecurityContextHolder.setContext(self.generateNewContext())
                
        else:
            self.logger.debug("No HttpSession currently exists - new SecurityContext instance associated with SecurityContextHolder")
            SecurityContextHolder.setContext(self.generateNewContext())
            
        self.logger.debug("Setting contextWhenChainProceeded to %s" % SecurityContextHolder.getContext())
        contextWhenChainProceeded = str(SecurityContextHolder.getContext())
             
        results = self.doNextFilter(environ, start_response)

        self.sessionStrategy.setHttpSession(self.SPRINGPYTHON_SECURITY_CONTEXT_KEY,
                                            pickle.dumps(SecurityContextHolder.getContext()))
        self.logger.debug("SecurityContext stored to HttpSession: '%s'" % SecurityContextHolder.getContext())

        SecurityContextHolder.clearContext()
        self.logger.debug("SecurityContextHolder cleared out, as request processing completed")

        return results