Announcement Announcement Module
Collapse
No announcement yet.
@PostFilter not working Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • @PostFilter not working

    Hi
    I am new to Spring Security 3 and was trying out @PostFilter on a method declared in an Interface but the returned Collection is not getting filtered.

    Here is the code:
    Code:
    public interface IProductService {
    
    	@PostFilter("(!filterObject.customersOnly) or (filterObject.customersOnly and hasRole('ROLE_USER'))")
    	Collection<Category> getCategories();
    }
    customerOnly is a boolean attribute in a domain object Category.

    I've added the following element on xyz-security.xml:
    Code:
    <global-method-security pre-post-annotations="enabled" />
    Could someone help me understand what am i missing?

    Thanks

  • #2
    Spring Security 3: @PostFilter not being detected

    Somehow the @PostFilter is not being detected, could someone help me understand the reason why it might be happening? Its an example code of the book Spring Security 3 by Peter Mularien.

    Thanks

    Comment


    • #3
      Hi! Thanks for trying out my example.

      Few questions:
      1> Do you have any other annotations that _are_ working?
      2> Are you making a call to this interface from another method in the same class?
      3> Are you instantiating this bean using Spring DI?
      4> Have you enabled DEBUG logging for org.springframework.security?

      Hope this helps, post back with answers to the questions. Typically annotations not working falls into the bucket of a general setup or configuration issue, and not that the annotation itself is broken.

      Comment


      • #4
        Spring Security 3: @PostFilter not being detected

        Hi Peter
        Thanks for the reply. I am actually testing the code of chapter 5 of your book on Spring Security 3.
        I do remember @PreAuthorize("hasRole('ROLE_ADMIN')") working from Interface IUserService.java when i tested it first but now when I am testing it again, it doesnt seem to be working the way it is supposed to, i.e. @PreAuthorize is not being detected either.

        If I use the security namespace from dogstore-security.xml, I am being shown an error saying:
        Code:
        Referenced file contains errors (http://www.springframework.org/schema/security/spring-security-3.0.xsd). For more information, right click on the message in the Problems View and select "Show Details..."
        , which on further look up says
        Code:
        XML document structure must start and end within the same entity on line number 517
        where number of lines in my dogstore-security.xml file is 80 only.

        But if use the namespace as below:
        Code:
        <beans:beans xmlns="http://www.springframework.org/schema/security"
          xmlns:beans="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:jdbc="http://www.springframework.org/schema/jdbc"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
                   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                   http://www.springframework.org/schema/jdbc  http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
                   http://www.springframework.org/schema/security
                   http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
        ...
        </beans:beans>
        .. it gives me an error
        Code:
        org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: You cannot use a spring-security-2.0.xsd schema with Spring Security 3.0. Please update your schema declarations to the 3.0 schema.
        The code that I am using is the code that came with the book Spring Security 3 only, so..

        1> Do you have any other annotations that _are_ working?
        -- I did see @PreAuthorize("hasRole('ROLE_ADMIN')") from Interface IUserService.java working earlier from chapter 5 but even this one doesnt seem to work anymore.

        2> Are you making a call to this interface from another method in the same class?
        -- No, I am calling it from the method getCategories() in HomeController.java

        3> Are you instantiating this bean using Spring DI?
        --Yes, the bean is being instantiated using DI only.

        4> Have you enabled DEBUG logging for org.springframework.security?
        -- It has been configured in the log4j.xml file you provided with the code.

        Could this be cause of the error that I am getting in the security config file? The application runs but it is not detecting the annotations for security.

        I wonder what was making @PreAuthorize work earlier?

        I wonder what am I missing here?

        Thanks

        Comment


        • #5
          Spring Security 3: @PostFilter not being detected

          Hello Peter
          I am no longer getting the org.springframework.beans.factory.parsing.BeanDefi nitionParsingException: Configuration problem: You cannot use a spring-security-2.0.xsd schema with Spring Security 3.0. Please update your schema declarations to the 3.0 schema. error as I changed the jars from 3.0.0 to 3.0.5 version of spring, sorry to bother you with that.

          But still when i use the jars provided with spring jars and source code form chapter 5 that came with the book I am getting that error in my XML file and not getting the security annotations detected.

          I am not getting those annotation from chapter 5 of ur book detected even when I am using the 3.0.5 version of the jars(considering the namespace changed according to that only).

          What blunder am I committing now?

          Thanks

          Comment


          • #6
            Hi,

            Glad you got the schema reference / runtime JARs figured out.

            Getting annotations working is definitely one of the most tricky aspects of the framework (IMO) for new users.

            Please make sure you that you are not getting any errors at all upon startup - carefully review all the logs. Also, if you have updated Spring to 3.0.5, make sure you have updated Spring Sec to 3.0.3 or higher, as Spring Framework 3.0.5 is not compatible with Spring Security 3.0.0.

            Please verify / post your <global-method-security> element (actually, go ahead and post your whole XML security configuration). Are you sure you have the correct settings to support @PostFilter (namely, pre-post-annotations="enabled")?

            Have you changed or enabled any AOP or AspectJ settings or configuration elements in the Spring context configuration? Fiddling with these kinds of things without understanding the effects (no offense meant here) can cause annotations to stop working, or work unexpectedly.

            Hope that helps! Post back when you get a chance and I will try to answer. Also (since this doesn't sound book-specific per se), please do search through the forum here for other suggestions that folks have had in the past.

            Best,
            Peter

            Comment


            • #7
              Hello Peter
              Here is complete security configuration file that I am using:
              Code:
              <?xml version="1.0" encoding="UTF-8"?>
              <beans:beans xmlns="http://www.springframework.org/schema/security"
              	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              	xmlns:beans="http://www.springframework.org/schema/beans"
              	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
              	xsi:schemaLocation="
              		http://www.springframework.org/schema/beans 
              		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
              		http://www.springframework.org/schema/jdbc  http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
              		http://www.springframework.org/schema/security 
              		http://www.springframework.org/schema/security/spring-security-3.0.3.xsd
              	">
                         
              	<global-method-security pre-post-annotations="enabled" />
              	<http auto-config="true" use-expressions="true">
              		<intercept-url pattern="/login.do" access="permitAll" /> 
              		<intercept-url pattern="/home.do" access="permitAll"/>
              		<intercept-url pattern="/account/*.do" access="hasRole('ROLE_USER') and fullyAuthenticated" />
              		<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>
              		<form-login login-page="/login.do"/>
              		<logout invalidate-session="true" logout-url="/logout" logout-success-url="/"/>
              		<remember-me key="jbcpPetStore" token-validity-seconds="3600" data-source-ref="dataSource"/>
              	</http>
              
              	<authentication-manager alias="authenticationManager">
              		<authentication-provider user-service-ref="jdbcUserServiceCustom"> 
              			<password-encoder ref="passwordEncoder">
              				<salt-source ref="saltSource"/>
              			</password-encoder>
              		</authentication-provider>
              	</authentication-manager>	
              	
              	<jdbc:embedded-database id="dataSource" type="HSQL">
              		<jdbc:script location="classpath:security-schema.sql"/>
              		<jdbc:script location="classpath:remember-me-schema.sql"/>
              		<jdbc:script location="classpath:test-users-groups-data.sql"/>		
              	</jdbc:embedded-database> 	
              
              </beans:beans>
              The jars that I am using are 3.0.5 release for both Security and Spring as well.

              Thanks for the reply again.

              Comment


              • #8
                Sorry for the delayed reply! One last thing to verify - can you confirm that you haven't added any of the <aop:...> declarations in another configuration file for the same ApplicationContext (e.g. in the case of the book, dogstore-base.xml)?

                If not (and you're still stuck), please set the log files to DEBUG, start up the application, and attach them to a reply and we can take a look. Alternatively, hook up a debugger and start stepping through your application initialization - although this may be hard, it will definitely be helpful to you to see how things are wired together. I can give you some tips on where to set breakpoints if you decide to go this route.

                Once last thing that may be a problem - have you turned off <context:component-scan> or otherwise changed how the IProductService implementation bean is picked up by the Spring ApplicationContext? A similar type of issue might be caused if you have modified the location / order of initialization of the Spring configuration files in web.xml.

                Anyway, the logs or a debugger will definitely tell us what's going on!

                Comment


                • #9
                  Hello Peter
                  Here is the dogstore-base.xml I am using:
                  Code:
                  <?xml version="1.0" encoding="UTF-8"?>
                  <beans xmlns="http://www.springframework.org/schema/beans"
                  	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  	xmlns:context="http://www.springframework.org/schema/context"
                  	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
                  	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
                             http://www.springframework.org/schema/jdbc  http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
                  		   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                  	">
                  
                  	<context:annotation-config />
                  	<context:component-scan base-package="com.packtpub.springsecurity"/>
                  
                  	<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder" />
                  	
                  	<bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource" >
                  		<property name="userPropertyToUse" value="salt"/>
                  	</bean>
                  	
                  	<bean class="com.packtpub.springsecurity.security.DatabasePasswordSecurerBean" init-method="secureDatabase" depends-on="dataSource">
                  		<property name="dataSource" ref="dataSource"/>	
                  	</bean>
                  	
                   	<bean id="jdbcUserServiceCustom" class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">
                  		<property name="dataSource" ref="dataSource"/>
                  		<property name="enableGroups" value="true"/>
                  		<property name="enableAuthorities" value="false"/>
                  		<property name="usersByUsernameQuery">
                  			<value>select username,password,enabled,salt from users where username = ?</value>
                  		</property>
                  	</bean>
                  
                  </beans>
                  I dont have any of the <aop: ... > configured or turned off <context:component-scan>.

                  I've attached the log file and a snap shot when i tried to run the application in debug mode. So "Customer Appreciation Special", which I am not supposed to be shown without being logged in as user with ROLE_USER is being shown.

                  log file link : http://www.mediafire.com/?x723gmvxkxy5kpp

                  image link: http://img820.imageshack.us/img820/4...beingdetec.png
                  Thanks for the reply.
                  Last edited by skipskipping; Jan 22nd, 2011, 06:21 AM.

                  Comment


                  • #10
                    Thanks again for the detailed reply. I don't see anything obvious in the logs - it looks like the @PostFilter is correctly picked up by your configuration, but I don't see it being hit when you make the getCategories call. I will try and reproduce with those same versions of Spring and Spring Sec, and get back to you later today with an answer. Have you tried stepping through the method call in a debugger to make sure that the method call is proxied (via AOP)?

                    Comment


                    • #11
                      Hi Peter
                      No, the method calls are not getting proxied via AOP.

                      I tried to put a simple advice across all the service classes (without forgetting to add the namespace schema), even that doesnt seem to work.

                      Code:
                      <bean id="loggingAdvice" class="com.packtpub.springsecurity.advice.PerformanceLoggingAdvice"/>
                      <aop:config>	
                      	<aop:pointcut id="allServiceClasses" 
                      		      expression="execution(* com.packtpub.springsecurity.service.I*Service.*(..))"/> 
                         	<aop:aspect ref="loggingAdvice">
                            		<aop:around method="timeInvocation" pointcut-ref="allServiceClasses"/>
                      	</aop:aspect>
                      </aop:config>
                      <aop:aspectj-autoproxy/>
                      Thanks again for the reply.

                      Comment


                      • #12
                        I compared your logging output with mine, from the same chapter / example. It looks like your ApplicationContexts are being processed in a different order than mine. In your web.xml file, do you have the following:

                        Code:
                           <context-param>
                            <param-name>contextConfigLocation</param-name>
                            <param-value>
                                /WEB-INF/dogstore-security.xml
                                /WEB-INF/dogstore-base.xml
                            </param-value>
                           </context-param>
                        Also, can you confirm that you have not added any AOP proxy declarations, beans, or anything else to dogstore-servlet.xml, except for the following lines which should be in there:

                        Code:
                            <context:annotation-config />
                            <context:component-scan base-package="com.packtpub.springsecurity.web"/>
                        It looks like your log file isn't the complete log, you should see stuff like this at the beginning, when the Spr Sec namespace handler starts processing your configuration:

                        Code:
                         INFO [main] (SpringSecurityCoreVersion.java:22) - You are running with Spring Security Core 3.0.5.RELEASE
                         INFO [main] (SecurityNamespaceHandler.java:57) - Spring Security 'config' module version is 3.0.5.RELEASE
                        I also noticed that your configuration is using JDK dynamic proxies - this can mean that you don't have a complete classpath to support AOP, for example, you do not have the AspectJ libraries included on the classpath. Can you make sure that all the Spring Dependencies are on the classpath and marked as exports to your web application (in Eclipse 3.5, this is Java EE Module Dependencies, in Eclipse 3.6, it's under Deployment Assembly).

                        Could you please post or attach your web.xml and we can check that out too? We'll get to the bottom of this sooner or later!

                        Comment


                        • #13
                          Hi Peter
                          Below are the dogstore-servlet.xml and web.xml files:
                          dogstore-servlet.xml:
                          Code:
                          <?xml version="1.0" encoding="UTF-8"?>
                          <beans xmlns="http://www.springframework.org/schema/beans"
                          	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                          	xmlns:context="http://www.springframework.org/schema/context"
                          	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
                          	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                          		http://www.springframework.org/schema/jdbc  http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
                          		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                          	">	
                          	<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
                          	   <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
                          	   <property name="prefix" value="/WEB-INF/views/"/>
                          	   <property name="suffix" value=".jsp"/>
                          	</bean>
                          
                          	<context:annotation-config />
                          	<context:component-scan base-package="com.packtpub.springsecurity"/>
                          </beans>
                          web.xml:
                          Code:
                          <?xml version="1.0" encoding="UTF-8"?>
                          <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="DogStoreApp" version="2.5">
                            <display-name>Dog Store</display-name>
                            <context-param>
                              <param-name>contextConfigLocation</param-name>
                              <param-value>
                          		/WEB-INF/dogstore-security.xml
                          		/WEB-INF/dogstore-base.xml
                          	</param-value>
                             </context-param>
                            <listener>
                              <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
                            </listener>
                            <servlet>
                              <servlet-name>dogstore</servlet-name>
                              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                              <load-on-startup>1</load-on-startup>
                            </servlet>
                            <servlet-mapping>
                              <servlet-name>dogstore</servlet-name>
                              <url-pattern>*.do</url-pattern>
                              <url-pattern>/home.do</url-pattern>
                            </servlet-mapping>
                            <filter>
                              <filter-name>springSecurityFilterChain</filter-name>
                              <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
                            </filter>
                            <filter-mapping>
                              <filter-name>springSecurityFilterChain</filter-name>
                              <url-pattern>/*</url-pattern>
                            </filter-mapping>
                            <welcome-file-list>
                              <welcome-file>home.do</welcome-file>
                            </welcome-file-list>
                          </web-app>
                          Am really sorry for mistakenly sending you the log file that missed the logging at the start of the application. Here is the log file from the top, that is including the logging that you mentioned in your last post.
                          Link to the log file: http://www.mediafire.com/?8caelrczrgt3itc

                          I have the following AOP-Alliance and AspectJ dependency jars in my lib folder along with other dependencies:
                          aopalliance-1.0
                          aspectjrt
                          aspectjtools
                          aspectjweaver
                          org.aspectj.matcher


                          Thanks again for the reply.

                          Comment


                          • #14
                            Ah!

                            I think what is happening is that you are putting components into 2 application contexts inadvertently, and this is causing strange binding behavior.

                            You can see that you have modified the dogstore-servlet.xml, which is the WebApplicationContext, to component-scan the entire project:

                            Code:
                            <context:component-scan base-package="com.packtpub.springsecurity"/>
                            Additionally, the dogstore-base.xml ApplicationContext is scanning the entire project:

                            Code:
                            <context:component-scan base-package="com.packtpub.springsecurity"/>
                            I admit that I don't fully know why you shouldn't do this, but I know that this definitely will cause problems with AOP and proxying, as well as weird binding errors (because you may end up with beans wired in unexpected ways). I have struggled with this on numerous occasions (including when writing the book!).

                            If you change dogstore-servlet.xml to automatically pick up only the com.packtpub.springsecurity.web package, and the dogstore-base.xml to pick up all the other packages (explicitly stated), I believe you'll find things will work again. It seems you've added some other packages that aren't part of the sample code from the book (which is a good thing!), and maybe you changed this when you added those new packages?

                            For reference, this particular sample has the following in dogstore-base.xml:

                            Code:
                                <context:component-scan base-package="com.packtpub.springsecurity.dao"/>
                                <context:component-scan base-package="com.packtpub.springsecurity.service"/>
                                <context:component-scan base-package="com.packtpub.springsecurity.security"/>
                            dogstore-servlet.xml:

                            Code:
                                <context:component-scan base-package="com.packtpub.springsecurity.web"/>
                            Try that out and let me know if it does/doesn't fix the issues you're seeing!

                            Note that I also have the following in dogstore-base.xml:
                            Code:
                            <aop:aspectj-autoproxy/>
                            You may want to try adding this, or experimenting with the aop namespace settings, if you find the proxies for AOP aren't behaving well with your application (this is sometimes a problem for people, especially when using explicit type casting).

                            Comment


                            • #15
                              Hi Peter

                              Yeah, It was the repeated declaration of <context:component-scan.. /> element only that was causing the issue.
                              Now everything seems to be working pretty smoothly.

                              Apologies for all the trouble caused to u. Quite a blunder it was.

                              Many many thanks

                              Comment

                              Working...
                              X