2014-10-22 2 views
0

Я пытаюсь добавить весеннюю безопасность к своему веб-приложению (от here), который должен поддерживать модель ролей и разрешений. Я не знаю, где недостающая часть в моей конфигурации, но @PreAuthorize не работает, и я не могу ее проследить. Вот мой контекстный файл приложения.Весенняя безопасность: управление доступом на основе ролей

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 

    <context:component-scan base-package="com.njb.app" /> 

    <import resource="db.xml" /> 

    <bean id="jdbcUserService" 
     class="com.nj.app.SpringSecurityDaoImpl"> 
      <property name="dataSource" ref="dataSource"/> 
      <property name="enableGroups" value="true" /> 
      <property name="enableAuthorities" value="false" /> 
      <property name="groupAuthoritiesByUsernameQuery"> 
       <value>SELECT R.SEC_ROLES, R.SEC_ROLES_ROLE_NAME, RI.SEC_RIGHT_NAME 
       FROM SEC_ROLES R 
       JOIN SEC_USER_ROLE UR on R.SEC_ROLES = UR.SEC_ROLE_ID 
       JOIN SEC_USERS U on U.SEC_USERS = UR.SEC_USER_ID 
       JOIN SEC_ROLE_RIGHT RR ON RR.SEC_ROLE_ID = R.SEC_ROLES 
       JOIN SEC_RIGHTS RI ON RI.SEC_RIGHT_ID = RR.SEC_RIGHT_ID 
       WHERE U.SEC_USERS_USERNAME=? 
      </value> 
      </property> 
    </bean> 

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
     destroy-method="close"> 
     <property name="driverClassName" value="${jdbc.driverClassName}" /> 
     <property name="url" value="${jdbc.url}" /> 
     <property name="username" value="${jdbc.username}" /> 
     <property name="password" value="${jdbc.password}" /> 
    </bean> 
</beans> 

файл весна-безопасности:

<?xml version="1.0" encoding="UTF-8"?> 

<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" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd"> 

<http auto-config="true" use-expressions="true"> 
    <!--<intercept-url pattern="/protected.jsf" access="isAuthenticated()" />--> 
    <intercept-url pattern="*/user/*" access="hasRole('LIST_USERSSSSS')" /> 
    <intercept-url pattern="/auth" access="permitAll()" /> 
</http> 

<!-- Use database authentication provider. --> 
<authentication-manager> 
    <authentication-provider user-service-ref="jdbcUserService"> 
    </authentication-provider> 
</authentication-manager> 

DB XML

<?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:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName"> 

    <bean id="placeholderConfig" 
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
     <property name="location" value="classpath:jdbc.properties" /> 
    </bean> 
     <bean id="loadTimeWeaver" 
     class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver" /> 

      <bean id="entityManagerFactory" 
       class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
       <property name="persistenceUnitName" value="PU" /> 
      </bean> 


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
     destroy-method="close"> 
     <property name="driverClassName" value="${jdbc.driverClassName}" /> 
     <property name="url" value="${jdbc.url}" /> 
     <property name="username" value="${jdbc.username}" /> 
     <property name="password" value="${jdbc.password}" /> 
</bean> 

    <!-- Transaction manager for JTA --> 
<tx:jta-transaction-manager /> 
<!-- enable the configuration of transactional behavior based on annotations --> 
<tx:annotation-driven /> 

<!-- checks for @Autowired beans --> 
<context:annotation-config/>  

<!-- Scan for Repository/Service annotations --> 
<context:component-scan base-package="...dao"/> 
<context:component-scan base-package="...service"/> 

и web.xml

<?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" 
    version="2.5"> 
    <context-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value> 
      /WEB-INF/root-context.xml 
      /WEB-INF/spring-security.xml 
     </param-value> 
    </context-param> 

    <!-- Enable Spring Security --> 
    <filter> 
     <filter-name>springSecurityFilterChain</filter-name> 
     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
    </filter> 

    <!-- Allow login pages with JSF which redirects to security check, therefore we have to add the forward entry here --> 
    <filter-mapping> 
     <filter-name>springSecurityFilterChain</filter-name> 
     <url-pattern>/*</url-pattern> 
     <dispatcher>FORWARD</dispatcher> 
     <dispatcher>REQUEST</dispatcher> 
    </filter-mapping> 

    <listener> 
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener> 

    <listener> 
     <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> 
    </listener> 

    <servlet> 
     <servlet-name>appServlet</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <init-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>/WEB-INF/servlet-context.xml</param-value> 
     </init-param> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 
</web-app> 

Вот как я использую предварительного блокирования средств на аннотацию

@PreAuthorize("hasRole('LIST_USERSS')") 
    @RequestMapping(value = "/findAll", method = RequestMethod.GET, produces = {"application/json"}) 
    @ResponseBody 
    public String findAll(HttpServletRequest request) { } 

и здесь запрос

http://localhost:8080/app/user/findAll.json? 
+0

Эта проблема очень обширна. Начните отладку приложения. Проверьте правильность инициализации DelegatingFilterProxy. Затем, если DelegatingFilterProxy фиксирует входящие запросы. Затем, если DelegatingFilterProxy запускает внутри себя фильтр AbstractPreAuthenticatedProcessingFilter. Затем создайте исключение или что-то, что прояснит, что действительно бездействует. Включите ведение журнала, что также может помочь. –

ответ

1

Чтобы получить @PreAuthorize и аналогичные аннотации к работе, добавьте в файл безопасности:

<global-method-security pre-post-annotations="enabled" /> 
+0

Я добавил это, и он все еще проходит @PreAuthorize – sina

+0

@sina Как выглядит ваш PreAuthorize и как вы используете этот метод? – holmis83

+0

Я добавил некоторые детали в конце вопроса, кстати, я хочу использовать свойство groupAuthoritiesByUsernameQuery с запросом, который я уже определил там. @ holmis83 – sina