Announcement Announcement Module
Collapse
No announcement yet.
SpringSecurity 2.02 ,How to do url resource write in database Page Title Module
Move Remove Collapse
This topic is closed
X
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • SpringSecurity 2.02 ,How to do url resource write in database

    <http auto-config="true" realm="Contacts Realm" access-denied-page="/erro.jsp" entry-point-ref="authenticationProcessingFilterEntryPoint" access-decision-manager-ref="httpRequestAccessDecisionManager" >
    <intercept-url pattern="/" access="ROLE_ADMIN,ROLE_ANONYMOUS" />
    <intercept-url pattern="/index.jsp" access="ROLE_ADMIN,ROLE_ANONYMOUS"/>
    <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN"/>
    <intercept-url pattern="/boss.jsp*" access="ROLE_ADMIN"/>
    <intercept-url pattern="/employee.jsp" access="ROLE_ADMIN"/>
    <intercept-url pattern="/manager.jsp" access="ROLE_ADMIN"/>
    <intercept-url pattern="/test.jsp" access="ROLE_ADMIN"/>
    <intercept-url pattern="/j_spring_security_switch_user" access="ROLE_ADMIN,ROLE_ANONYMOUS"/>
    <intercept-url pattern="/**" access="ROLE_ADMIN,ROLE_ANONYMOUS"/><!-- 只有为ROLE_USER 才能访问本系统的http资源 -->
    <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" login-processing-url="/j_acegi_security_check" default-target-url="/index.jsp" />
    <logout logout-success-url="/login?login_error=2" logout-url="/login?login_error=4"/>
    <anonymous granted-authority="ROLE_ANONYMOUS" key="doesNotMatter" username="anonymousUser"/>
    </http>


    I want to <intercept-url ... write in database ,but i don't know how to do?

  • #2
    You can add an authentication intercepter if that is what you mean. Please elaborate.

    Comment


    • #3
      Originally posted by cablepuff
      you have to use the bean approach.

      Code:
      public class CustomObjectDefinitionServiceImpl
      implements FilterInvocationDefinitionSource  {
          private AclDao aclDao;
          private ApplicationFeatureDao applicationFeatureDao;
          private UrlMatcher urlMatcher;
      
          public AclDao getAclDao() {
              return this.aclDao;
          }
      
          public void setAclDao(AclDao aclDao) {
              this.aclDao = aclDao;
          }
      
          public ApplicationFeatureDao getApplicationFeatureDao() {
              return this.applicationFeatureDao;
          }
          public void setApplicationFeatureDao(ApplicationFeatureDao applicationFeatureDao) {
              this.applicationFeatureDao = applicationFeatureDao;
          }
      
          public UrlMatcher getUrlMatcher() {
              return this.urlMatcher;
          }
          public void setUrlMatcher(UrlMatcher urlMatcher) {
              this.urlMatcher = urlMatcher;
          }
      
          private DefaultFilterInvocationDefinitionSource getCustomFid() {
              LinkedHashMap<RequestKey, ConfigAttributeDefinition> requestMap = new LinkedHashMap<RequestKey, ConfigAttributeDefinition>();
              List<ApplicationFeature> applicationFeatures = this.applicationFeatureDao.getAllApplicationFeature();
              for (ApplicationFeature applicationFeature : applicationFeatures)
              {
                  Application application = applicationFeature.getApplication();
                  Features feature = applicationFeature.getFeature();
                  final String localAntPath = "/" + application.getName() + "/" + feature.getName() + "**";
                  List<Group> groups = this.aclDao.getAllGroupThatCanAccessApplicationAndFeature(application, feature);
                  List<ConfigAttribute> configList = new LinkedList<ConfigAttribute>();
                  for (Group group : groups)
                  {
                      configList.add(new SecurityConfig(group.getAuthority()));
                  }
                  ConfigAttributeDefinition cad = new ConfigAttributeDefinition(configList);
                  RequestKey requestKey = new RequestKey(localAntPath);
                  requestMap.put(requestKey, cad);
              }
              return new DefaultFilterInvocationDefinitionSource(this.urlMatcher, requestMap);
          }
      
      
      
          @Override
          public ConfigAttributeDefinition getAttributes(Object obj)
                  throws IllegalArgumentException {
                return this.getCustomFid().getAttributes(obj);
          }
      
          @Override
          public Collection<?> getConfigAttributeDefinitions() {
              return this.getCustomFid().getConfigAttributeDefinitions();
          }
      
          @SuppressWarnings("unchecked")
          @Override
          public boolean supports(Class clazz) {
              return FilterInvocation.class.isAssignableFrom(clazz);
          }
      }
      Can you please explain in more detail what is ApplicationFeature, Feature and Application in context of your application?

      What getCustomFid() should do?

      Please show me too the spring security xml.

      Thanks in advance

      Comment


      • #4
        Can you show me the XML ?

        Originally posted by cablepuff
        you have to use the bean approach.

        Code:
        public class CustomObjectDefinitionServiceImpl
        implements FilterInvocationDefinitionSource  {
            private AclDao aclDao;
            private ApplicationFeatureDao applicationFeatureDao;
            private UrlMatcher urlMatcher;
        
            public AclDao getAclDao() {
                return this.aclDao;
            }
        
            public void setAclDao(AclDao aclDao) {
                this.aclDao = aclDao;
            }
        
            public ApplicationFeatureDao getApplicationFeatureDao() {
                return this.applicationFeatureDao;
            }
            public void setApplicationFeatureDao(ApplicationFeatureDao applicationFeatureDao) {
                this.applicationFeatureDao = applicationFeatureDao;
            }
        
            public UrlMatcher getUrlMatcher() {
                return this.urlMatcher;
            }
            public void setUrlMatcher(UrlMatcher urlMatcher) {
                this.urlMatcher = urlMatcher;
            }
        
            private DefaultFilterInvocationDefinitionSource getCustomFid() {
                LinkedHashMap<RequestKey, ConfigAttributeDefinition> requestMap = new LinkedHashMap<RequestKey, ConfigAttributeDefinition>();
                List<ApplicationFeature> applicationFeatures = this.applicationFeatureDao.getAllApplicationFeature();
                for (ApplicationFeature applicationFeature : applicationFeatures)
                {
                    Application application = applicationFeature.getApplication();
                    Features feature = applicationFeature.getFeature();
                    final String localAntPath = "/" + application.getName() + "/" + feature.getName() + "**";
                    List<Group> groups = this.aclDao.getAllGroupThatCanAccessApplicationAndFeature(application, feature);
                    List<ConfigAttribute> configList = new LinkedList<ConfigAttribute>();
                    for (Group group : groups)
                    {
                        configList.add(new SecurityConfig(group.getAuthority()));
                    }
                    ConfigAttributeDefinition cad = new ConfigAttributeDefinition(configList);
                    RequestKey requestKey = new RequestKey(localAntPath);
                    requestMap.put(requestKey, cad);
                }
                return new DefaultFilterInvocationDefinitionSource(this.urlMatcher, requestMap);
            }
        
        
        
            @Override
            public ConfigAttributeDefinition getAttributes(Object obj)
                    throws IllegalArgumentException {
                  return this.getCustomFid().getAttributes(obj);
            }
        
            @Override
            public Collection<?> getConfigAttributeDefinitions() {
                return this.getCustomFid().getConfigAttributeDefinitions();
            }
        
            @SuppressWarnings("unchecked")
            @Override
            public boolean supports(Class clazz) {
                return FilterInvocation.class.isAssignableFrom(clazz);
            }
        }
        Can you show me the XML ?
        Thanks !

        Comment


        • #5
          Code:
          <!--  authorization -->
          <bean id="filterSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor" autowire="autodetect">
                <property name="accessDecisionManager" ref="accessDecisionManager"/>
                <property name="validateConfigAttributes" value="true"/>
                <property name="objectDefinitionSource" ref="security.objectDefinitionService"/>
           </bean>
          i created bean for that.

          2.) application feature are urls

          Comment


          • #6
            Originally posted by cablepuff View Post
            Code:
            <!--  authorization -->
            <bean id="filterSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor" autowire="autodetect">
                  <property name="accessDecisionManager" ref="accessDecisionManager"/>
                  <property name="validateConfigAttributes" value="true"/>
                  <property name="objectDefinitionSource" ref="security.objectDefinitionService"/>
             </bean>
            i created bean for that.

            2.) application feature are urls
            i am very thanks !

            Comment


            • #7
              Originally posted by cablepuff View Post
              i created bean for that.

              2.) application feature are urls
              could you show me ApplicationFeature's code please ?

              and what's aclDao.getAllGroupThatCanAccessApplicationAndFeatu re(application, feature)?

              Thanks in advance

              Comment


              • #8
                Originally posted by cablepuff View Post
                Code:
                <!--  authorization -->
                <bean id="filterSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor" autowire="autodetect">
                      <property name="accessDecisionManager" ref="accessDecisionManager"/>
                      <property name="validateConfigAttributes" value="true"/>
                      <property name="objectDefinitionSource" ref="security.objectDefinitionService"/>
                 </bean>
                i created bean for that.

                2.) application feature are urls
                Thanks.

                I have made in same way old acegi work, declaring all beans and implement DatabaseObjectDefinition. It is working, but I am not happening with it.

                What about if you write an complete article showing only purpose of DatabaseObjectDefinition?

                You show as how is your tables (url and roles relashionships), what it is inside? your xml? and your beans?

                Hope you answers me,

                Thanks,

                Comment


                • #9
                  My Solution

                  I am using Spring with Hibernate and ZK Framework (www.zkoss.org)

                  1. DATABASE
                  CARGO = ROLE
                  create table CARGO (
                  ID numeric(18, 0) identity(1,1),
                  NOME varchar(100) unique not null,
                  SITUACAO int default 1 not null,
                  primary key (ID)
                  );

                  create table SUBMENU (
                  ID numeric(18, 0) identity(1,1),
                  NOME varchar(255) not null,
                  URL varchar(255),
                  SUBMENU_ID varchar(50) unique not null,
                  MENU numeric(18, 0) not null,
                  DESCRITIVO varchar(255),
                  SITUACAO int default 1 not null,
                  primary key (ID),
                  foreign key (MENU) references MENU(ID)
                  );

                  create table CARGO_SUBMENU (
                  CARGO numeric(18, 0),
                  SUBMENU numeric(18, 0),
                  primary key (CARGO, SUBMENU),
                  foreign key (CARGO) references CARGO(ID),
                  foreign key (SUBMENU) references SUBMENU(ID)
                  );

                  Comment


                  • #10
                    2. XML
                    Code:
                    <?xml version="1.0" encoding="UTF-8"?>
                    
                    <!--
                      - Application context containing authentication, channel security and web URI beans.
                    -->
                                            
                    <beans xmlns="http://www.springframework.org/schema/beans"
                    	xmlns:security="http://www.springframework.org/schema/security"
                    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                    						http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.1.xsd">                        
                    	
                    	<bean id="springSecurityFilterChain" class="org.springframework.security.util.FilterChainProxy">
                       		<property name="filterInvocationDefinitionSource">
                                <value><![CDATA[
                    	       		CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
                        	  		PATTERN_TYPE_APACHE_ANT
                          			/js/**=#NONE# 
                    				/img/**=#NONE#
                    				/css/**=#NONE# 
                    				/zkau/**=#NONE#
                          			/**=httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,rememberMeProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterSecurityInterceptor
                                ]]></value>
                            </property>
                    	</bean>
                    
                    	<bean id="httpSessionContextIntegrationFilter" class="org.springframework.security.context.HttpSessionContextIntegrationFilter" />
                    
                    	<bean id="logoutFilter" class="org.springframework.security.ui.logout.LogoutFilter">
                    		<constructor-arg value="/login.zul" />
                    		<constructor-arg>
                    			<list>
                    				<ref bean="rememberMeServices" />
                    				<bean class="org.springframework.security.ui.logout.SecurityContextLogoutHandler" />
                    			</list>
                    		</constructor-arg>
                    		<property name="filterProcessesUrl" value="/j_spring_security_logout" />
                    	</bean>
                    
                    	<bean id="authenticationProcessingFilter" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilter">
                    		<property name="defaultTargetUrl" value="/zul/layout.zul" />
                    		<property name="authenticationFailureUrl" value="/login.zul?login_error=1" />		
                    		<property name="filterProcessesUrl" value="/j_spring_security_check" />
                    		<property name="usernameParameter" value="j_username" />
                    		<property name="passwordParameter" value="j_password" />
                    		<property name="authenticationManager" ref="authenticationManager" />
                    		<property name="rememberMeServices" ref="rememberMeServices" />
                    	</bean>
                    
                    	<bean id="securityContextHolderAwareRequestFilter" class="org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter" />
                    
                    	<bean id="rememberMeProcessingFilter" class="org.springframework.security.ui.rememberme.RememberMeProcessingFilter">
                    		<property name="authenticationManager" ref="authenticationManager" />
                    		<property name="rememberMeServices" ref="rememberMeServices" />
                    	</bean>
                    
                    	<bean id="anonymousProcessingFilter" class="org.springframework.security.providers.anonymous.AnonymousProcessingFilter">
                    		<property name="key" value="doesNotMatter" />
                    		<property name="userAttribute" value="roleAnonymous,ROLE_ANONYMOUS" />
                    	</bean>
                    
                    	<bean id="exceptionTranslationFilter" class="org.springframework.security.ui.ExceptionTranslationFilter">
                    		<property name="authenticationEntryPoint">
                    			<bean class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint">
                    				<property name="loginFormUrl" value="/login.zul" />
                    				<property name="forceHttps" value="false" />
                    			</bean>
                    		</property>
                    		<property name="accessDeniedHandler">
                    			<bean class="org.springframework.security.ui.AccessDeniedHandlerImpl">
                    				<property name="errorPage" value="/403.zul" />
                    			</bean>
                    		</property>
                    	</bean>  
                    
                    	<bean id="filterSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor">
                    		<property name="authenticationManager" ref="authenticationManager" />
                    		<property name="accessDecisionManager" ref="accessDecisionManager" />
                    		<property name="objectDefinitionSource" ref="databaseObjectDefinitionSource" />
                    	</bean>
                    	
                    	<bean id="databaseObjectDefinitionSource" class="com.nemada.gescarga.util.DatabaseObjectDefinitionSource" >
                    		<constructor-arg ref="cargaService" />
                    		<constructor-arg ref="antUrlPathMatcher" /> 
                    	</bean>
                    	
                    	<bean id="antUrlPathMatcher" class="org.springframework.security.util.AntUrlPathMatcher" />
                    	
                    	<bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">
                    		<property name="allowIfAllAbstainDecisions" value="false" />
                    		<property name="decisionVoters">
                    			<list>
                    				<bean class="org.springframework.security.vote.RoleVoter" >
                    					<property name="rolePrefix" value="" />	
                    				</bean>
                    				<bean class="org.springframework.security.vote.AuthenticatedVoter"/>
                    			</list>
                    		</property>
                    	</bean>
                    	
                    	<bean id="rememberMeServices" class="org.springframework.security.ui.rememberme.TokenBasedRememberMeServices">
                    		<property name="key" value="MOZAMBIQUE-MLI-92-59" />
                    		<property name="parameter" value="_spring_security_remember_me" />
                    		<property name="cookieName" value="SPRING_SECURITY_REMEMBER_ME_COOKIE" />
                    		<property name="tokenValiditySeconds" value="1209600" /><!-- 14 days -->		
                    		<property name="userDetailsService" ref="cargaService" />		
                    	</bean>
                    	
                    	<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
                    		<property name="providers">
                    			<list>
                    				<ref bean="daoAuthenticationProvider" />
                    				<ref bean="anonymousAuthenticationProvider" />
                    				<ref bean="rememberMeAuthenticationProvider" />				
                    			</list>
                    		</property>
                    	</bean>
                    	
                    	<bean id="daoAuthenticationProvider" class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
                    		<property name="userDetailsService" ref="cargaService" />
                    		<property name="passwordEncoder" ref="passwordEncoder" />
                    		<!-- <property name="userCache">
                    			<bean
                    				class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
                    				<property name="cache">
                    					<bean
                    						class="org.springframework.cache.ehcache.EhCacheFactoryBean">
                    						<property name="cacheManager">
                    							<bean
                    								class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
                    						</property>
                    						<property name="cacheName" value="userCache" />
                    					</bean>
                    				</property>
                    			</bean>
                    		</property>
                    		 -->
                    	</bean>
                    	 
                    	<bean id="passwordEncoder" class="org.springframework.security.providers.encoding.ShaPasswordEncoder">
                        	<!-- strength - EX: 1, 256, 384, 512 -->
                        	<constructor-arg value="256"/>
                     	</bean>
                     	
                     	<bean id="anonymousAuthenticationProvider" class="org.springframework.security.providers.anonymous.AnonymousAuthenticationProvider">
                    		<property name="key" value="doesNotMatter" />
                    	</bean>
                    	
                     	<bean id="rememberMeAuthenticationProvider" class="org.springframework.security.providers.rememberme.RememberMeAuthenticationProvider">
                    		<property name="key" value="MOZAMBIQUE-MLI-92-59" />
                    	</bean>
                    	
                    	<!-- Disable a user after a number of failed logins listener -->
                    	<!--<bean id="applicationListenerImpl" class="com.nemada.gescarga.listener.ApplicationListenerImpl"/>-->
                    
                     	<!-- Automatically receives AuthenticationEvent messages --> 
                    	<bean id="loggerListener" class="org.springframework.security.event.authentication.LoggerListener"/>
                    	
                    </beans>
                    Last edited by sousa1981; Sep 8th, 2008, 12:40 PM.

                    Comment


                    • #11
                      3. JavaBeans:
                      Code:
                      package com.nemada.gescarga.util;
                      
                      import java.util.Arrays;
                      import java.util.Collection;
                      import java.util.Collections;
                      import java.util.HashMap;
                      import java.util.HashSet;
                      import java.util.Iterator;
                      import java.util.LinkedHashMap;
                      import java.util.Map;
                      import java.util.Set;
                      
                      import org.apache.log4j.Logger;
                      import org.springframework.security.ConfigAttributeDefinition;
                      import org.springframework.security.intercept.web.FilterInvocation;
                      import org.springframework.security.intercept.web.FilterInvocationDefinitionSource;
                      import org.springframework.security.util.UrlMatcher;
                      
                      import com.nemada.gescarga.service.CargaService;
                      
                      @SuppressWarnings("unchecked")
                      public class DatabaseObjectDefinitionSource implements FilterInvocationDefinitionSource {
                      	
                      	private static final Logger log = Logger.getLogger(DatabaseObjectDefinitionSource.class);
                      	
                      	private static final Set HTTP_METHODS = new HashSet(Arrays.asList(new String[]{ "DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT", "TRACE" }));
                      
                          /**
                           * Non method-specific map of URL patterns to <tt>ConfigAttributeDefinition</tt>s
                           * TODO: Store in the httpMethod map with null key.
                           */
                      	private Map requestMap = new LinkedHashMap();
                          
                          /** Stores request maps keyed by specific HTTP methods */
                      	private Map httpMethodMap = new HashMap();
                      
                          private UrlMatcher urlMatcher;
                      
                          private boolean stripQueryStringFromUrls;
                          
                          /**
                           * Creates a FilterInvocationDefinitionSource with the supplied URL matching strategy.
                           * @param urlMatcher
                           */
                      	public DatabaseObjectDefinitionSource(CargaService cargaService, UrlMatcher urlMatcher) {    	
                              this(cargaService, urlMatcher, new LinkedHashMap());        
                          }
                      
                          /**
                           * Creates a FilterInvocationDefinitionSource with the supplied URL matching strategy.
                           * @param urlMatcher
                           */
                          DatabaseObjectDefinitionSource(UrlMatcher urlMatcher) {
                              this.urlMatcher = urlMatcher;
                          }
                          
                          /**
                           * Builds the internal request map from the supplied map. The key elements should be of type {@link RequestKey},
                           * which contains a URL path and an optional HTTP method (may be null). The path stored in the key will depend on 
                           * the type of the supplied UrlMatcher.
                           * 
                           * @param urlMatcher typically an ant or regular expression matcher.
                           * @param requestMap order-preserving map of <RequestKey, ConfigAttributeDefinition>.
                           */
                          public DatabaseObjectDefinitionSource(CargaService cargaService, UrlMatcher urlMatcher, LinkedHashMap requestMap) {
                              this.urlMatcher = urlMatcher;
                      
                              requestMap = (LinkedHashMap)cargaService.getRolesAndUrl(); 
                              
                              Iterator iterator = requestMap.entrySet().iterator();
                      
                              while (iterator.hasNext()) {
                                  Map.Entry entry = (Map.Entry) iterator.next();
                                  RequestKey reqKey = (RequestKey) entry.getKey();
                                  addSecureUrl(reqKey.getUrl(), reqKey.getMethod(), (ConfigAttributeDefinition) entry.getValue());
                              }
                          }
                      
                          //~ Methods ========================================================================================================
                      
                          void addSecureUrl(String pattern, ConfigAttributeDefinition attr) {
                              addSecureUrl(pattern, null, attr);
                          }
                      
                          /**
                           * Adds a URL-ConfigAttributeDefinition pair to the request map, first allowing the <tt>UrlMatcher</tt> to
                           * process the pattern if required, using its <tt>compile</tt> method. The returned object will be used as the key
                           * to the request map and will be passed back to the <tt>UrlMatcher</tt> when iterating through the map to find
                           * a match for a particular URL.
                           */
                      	void addSecureUrl(String pattern, String method, ConfigAttributeDefinition attr) {
                              Map mapToUse = getRequestMapForHttpMethod(method);
                      
                              mapToUse.put(urlMatcher.compile(pattern), attr);
                      
                              if (log.isDebugEnabled()) log.debug("Added URL pattern: " + pattern + "; attributes: " + attr +
                                          (method == null ? "" : " for HTTP method '" + method + "'"));
                          }
                      
                          /**
                           * Return the HTTP method specific request map, creating it if it doesn't already exist.
                           * @param method GET, POST etc
                           * @return map of URL patterns to <tt>ConfigAttributeDefinition</tt>s for this method.
                           */
                      	private Map getRequestMapForHttpMethod(String method) {
                              if (method == null) {
                                  return requestMap;
                              }
                              if (!HTTP_METHODS.contains(method)) {
                                  throw new IllegalArgumentException("Unrecognised HTTP method: '" + method + "'");
                              }
                      
                              Map methodRequestmap = (Map) httpMethodMap.get(method);
                      
                              if (methodRequestmap == null) {
                                  methodRequestmap = new LinkedHashMap();
                                  httpMethodMap.put(method, methodRequestmap);
                              }
                      
                              return methodRequestmap;
                          }
                      
                      	public Collection getConfigAttributeDefinitions() {    	
                              return Collections.unmodifiableCollection(getRequestMap().values());
                          }
                      
                          public ConfigAttributeDefinition getAttributes(Object object) throws IllegalArgumentException {
                              if ((object == null) || !this.supports(object.getClass())) {
                                  throw new IllegalArgumentException("Object must be a FilterInvocation");
                              }
                      
                              String url = ((FilterInvocation) object).getRequestUrl();
                              String method = ((FilterInvocation) object).getHttpRequest().getMethod();
                      
                              return lookupAttributes(url, method);
                          }
                      
                          protected ConfigAttributeDefinition lookupAttributes(String url) {
                              return lookupAttributes(url, null);
                          }
                      
                          /**
                           * Performs the actual lookup of the relevant <code>ConfigAttributeDefinition</code> for the specified
                           * <code>FilterInvocation</code>.
                           * <p>
                           * By default, iterates through the stored URL map and calls the
                           * {@link UrlMatcher#pathMatchesUrl(Object path, String url)} method until a match is found.
                           * <p>
                           * Subclasses can override if required to perform any modifications to the URL.
                           *
                           * @param url the URI to retrieve configuration attributes for
                           * @param method the HTTP method (GET, POST, DELETE...).
                           *
                           * @return the <code>ConfigAttributeDefinition</code> that applies to the specified <code>FilterInvocation</code>
                           * or null if no match is found
                           */
                      	public ConfigAttributeDefinition lookupAttributes(String url, String method) {
                          	if (log.isDebugEnabled()) log.debug("lookupAttributes url: '" + url + "'; method: '" + method + "'");
                              if (stripQueryStringFromUrls) {
                                  // Strip anything after a question mark symbol, as per SEC-161. See also SEC-321
                                  int firstQuestionMarkIndex = url.indexOf("?");
                      
                                  if (firstQuestionMarkIndex != -1) {
                                      url = url.substring(0, firstQuestionMarkIndex);
                                  }            
                              }
                      
                              if (urlMatcher.requiresLowerCaseUrl()) {
                                  url = url.toLowerCase();
                      
                                  if (log.isDebugEnabled()) log.debug("Converted URL to lowercase, from: '" + url + "'; to: '" + url + "'");
                              }
                      
                              ConfigAttributeDefinition attributes = null;
                      
                              Map methodSpecificMap = (Map) httpMethodMap.get(method);
                      
                              if (methodSpecificMap != null) {
                                  attributes = lookupUrlInMap(methodSpecificMap, url);
                              }
                      
                              if (attributes == null) {
                                  attributes = lookupUrlInMap(requestMap, url);
                              }
                      
                              return attributes;
                          }
                      
                      	private ConfigAttributeDefinition lookupUrlInMap(Map requestMap, String url) {
                          	if (log.isDebugEnabled()) log.debug("lookupUrlInMap requestMap: '" + requestMap + "'; url: '" + url + "'");
                              Iterator entries = requestMap.entrySet().iterator();
                      
                              while (entries.hasNext()) {
                                  Map.Entry entry = (Map.Entry) entries.next();
                                  Object p = entry.getKey();
                                  boolean matched = urlMatcher.pathMatchesUrl(p, url);
                      
                                  if (log.isDebugEnabled()) log.debug("Candidate is: '" + url + "'; pattern is " + p + "; matched=" + matched);
                      
                                  if (matched) {
                                      return (ConfigAttributeDefinition) entry.getValue();
                                  }
                              }
                      
                              return null;
                          }
                      
                      	public boolean supports(Class clazz) {
                              return FilterInvocation.class.isAssignableFrom(clazz);
                          }
                      
                          public int getMapSize() {
                              return this.requestMap.size();
                          }
                      
                      	Map getRequestMap() {  
                              return requestMap;
                          }
                      
                          protected UrlMatcher getUrlMatcher() {
                              return urlMatcher;
                          }
                      
                          public boolean isConvertUrlToLowercaseBeforeComparison() {
                              return urlMatcher.requiresLowerCaseUrl();
                          }
                      
                          public void setStripQueryStringFromUrls(boolean stripQueryStringFromUrls) {
                              this.stripQueryStringFromUrls = stripQueryStringFromUrls;
                          }
                      
                      }

                      Comment


                      • #12
                        Code:
                        package com.nemada.gescarga.util;
                        
                        public class RequestKey {
                            private String url;
                            private String method;
                        
                            public RequestKey(String url) {
                                this(url, null);
                            }
                        
                            public RequestKey(String url, String method) {
                                this.url = url;
                                this.method = method;
                            }
                            
                            String getUrl() {
                                return url;
                            }
                        
                            String getMethod() {
                                return method;
                            }
                        
                            public int hashCode() {
                                int code = 31;
                                code ^= url.hashCode();
                                
                                if (method != null) {
                                    code ^= method.hashCode();
                                }
                        
                                return code;
                            }
                        
                            public boolean equals(Object obj) {
                                if (!(obj instanceof RequestKey)) {
                                    return false;
                                }
                        
                                RequestKey key = (RequestKey) obj;
                        
                                if (!url.equals(key.url)) {
                                    return false;
                                }
                                
                                if (method == null) {
                                	return key.method == null;
                                }
                        
                                return method.equals(key.method);        
                            }
                        }

                        Comment


                        • #13
                          Improvement

                          replace the old bean databaseObjectDefinitionSource to be:

                          Code:
                          <bean id="databaseObjectDefinitionSource" class="org.springframework.security.intercept.web.DefaultFilterInvocationDefinitionSource" >		
                          		<constructor-arg ref="antUrlPathMatcher" /> 
                          		<constructor-arg ref="requestMap" />
                          	</bean>
                          	
                          	<bean id="antUrlPathMatcher" class="org.springframework.security.util.AntUrlPathMatcher" />
                          	
                          	<bean id="requestMap" class="com.nemada.gescarga.util.RequestMapFactoryBean" init-method="init"/>
                          requestMap bean implements as follow:
                          Code:
                          package com.nemada.gescarga.util;
                          
                          import java.util.LinkedHashMap;
                          
                          import org.springframework.beans.factory.FactoryBean;
                          import org.springframework.beans.factory.annotation.Autowired;
                          import org.springframework.security.ConfigAttributeDefinition;
                          import org.springframework.security.intercept.web.RequestKey;
                          import org.springframework.security.vote.AuthenticatedVoter;
                          
                          import com.nemada.gescarga.service.CargaService;
                          
                          /**
                           * @author marcos.sousa
                           */
                          @SuppressWarnings("unchecked")
                          public class RequestMapFactoryBean implements FactoryBean {
                          	
                          	@Autowired
                          	private CargaService cargaService;
                          	
                          	private LinkedHashMap<RequestKey, ConfigAttributeDefinition> requestMap;	
                          	
                          	public void init() {
                          		requestMap = (LinkedHashMap)cargaService.getRolesAndUrl(); 
                          	}
                          	
                          	@Override
                          	public Object getObject() throws Exception {
                          		if (requestMap == null) {
                          			init();
                          		}
                          		return requestMap;
                          	}
                          
                          	@Override
                          	public Class getObjectType() {
                          		return LinkedHashMap.class;
                          	}
                          
                          	@Override
                          	public boolean isSingleton() {
                          		return true;
                          	}	
                          	
                          }
                          As you can see, you will not more need RequestMap.java in your package and no need of an scratch DatabaseObjectDefinitionSource (since we used DefaultFilterInvocationDefinitionSource)

                          Now, remember to use dao cache!

                          Comment


                          • #14
                            Using new namespace

                            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:security="http://www.springframework.org/schema/security"
                                xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                                       	http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd">  
                                
                                <security:http auto-config="true" lowercase-comparisons="false" session-fixation-protection="none" access-denied-page="/403.zul">
                                	<security:intercept-url pattern="/css/**" filters="none"/>
                                	<security:intercept-url pattern="/img/**" filters="none"/>
                                	<security:intercept-url pattern="/js/**" filters="none"/>
                                	<security:intercept-url pattern="/zkau/**" filters="none"/>
                                	<security:intercept-url pattern="/zkau**" filters="none"/>
                                    <security:form-login login-page="/login.zul" authentication-failure-url="/login.zul?login_error=1" default-target-url="/zul/layout.zul"/>
                                    <security:logout logout-success-url="/login.zul"/>
                                    <security:remember-me user-service-ref="cargaService" key="yourKey-xxx-@#17Ux-x" />
                                </security:http>
                                   
                            	<security:authentication-manager alias="authenticationManager"/> 
                                
                                <bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">
                            		<property name="allowIfAllAbstainDecisions" value="false" />
                            		<property name="decisionVoters">
                            			<list>
                            				<bean class="org.springframework.security.vote.RoleVoter" >
                            					<property name="rolePrefix" value="" />	
                            				</bean>
                            				<bean class="org.springframework.security.vote.AuthenticatedVoter"/>
                            			</list>
                            		</property>
                            	</bean>
                            	   
                                <bean id="filterSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor">
                                	<security:custom-filter before="FILTER_SECURITY_INTERCEPTOR" />
                            		<property name="authenticationManager" ref="authenticationManager" />
                            		<property name="accessDecisionManager" ref="accessDecisionManager" />
                            		<property name="objectDefinitionSource" ref="databaseObjectDefinitionSource" />
                            	</bean>
                            	
                            	<bean id="databaseObjectDefinitionSource" class="org.springframework.security.intercept.web.DefaultFilterInvocationDefinitionSource" >		
                            		<constructor-arg ref="antUrlPathMatcher" /> 
                            		<constructor-arg ref="requestMap" />
                            	</bean>
                            	
                            	<bean id="antUrlPathMatcher" class="org.springframework.security.util.AntUrlPathMatcher" />
                            	
                            	<bean id="requestMap" class="com.nemada.gescarga.util.RequestMapFactoryBean" init-method="init"/>
                            	
                                <security:authentication-provider user-service-ref="cargaService">
                                    <security:password-encoder ref="passwordEncoder" />
                                </security:authentication-provider>
                                
                                <bean id="passwordEncoder" class="org.springframework.security.providers.encoding.ShaPasswordEncoder">
                                	<constructor-arg value="256"/>
                             	</bean>
                            </beans>
                            I found that using this <security:custom-filter before="FILTER_SECURITY_INTERCEPTOR" /> can tell spring to use my definition or inject addition info, so this was what I was trying to archive long time ago.

                            Comment


                            • #15
                              Originally posted by cablepuff View Post
                              Code:
                              <!--  authorization -->
                              <bean id="filterSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor" autowire="autodetect">
                                    <property name="accessDecisionManager" ref="accessDecisionManager"/>
                                    <property name="validateConfigAttributes" value="true"/>
                                    <property name="objectDefinitionSource" ref="security.objectDefinitionService"/>
                               </bean>
                              i created bean for that.

                              2.) application feature are urls
                              Hello.

                              Can you show the entire applicationContext.xml (because I have doubts about how other related beans are declared).

                              Thanks in advance.

                              Jerry - Brazil

                              Comment

                              Working...
                              X