Spring框架,PreAuthorize控件中的自定义函数

时间:2015-03-29 14:10:42

标签: java spring spring-mvc spring-security

我是春天新手,我正在努力学习开发一个简单的应用程序。

这是数据库的架构: http://i.imgur.com/69czuV5.png

非常简单,每个用户必须从登录开始,一旦他们这样做,就会显示管理员所在团队的列表。该信息存储在表 team_members

INSERT INTO team_members (user_id, team_id, role) VALUES ('1', '1', 'admin');
INSERT INTO team_members (user_id, team_id, role) VALUES ('1', '2', 'admin');
INSERT INTO team_members (user_id, team_id, role) VALUES ('2', '2', 'player');
INSERT INTO team_members (user_id, team_id, role) VALUES ('2', '3', 'admin');

当用户尝试编辑或访问页面以编辑其中一个团队时,我的问题就出现了。这是我的控制器

@RequestMapping(value="teams/{id}/edit", method=RequestMethod.GET)
    public ModelAndView editTeamPage(@PathVariable Integer id) {
        ModelAndView modelAndView = new ModelAndView("edit-team-form");
        Team team = teamService.getTeam(id);
        modelAndView.addObject("team",team);
        return modelAndView;
    }

为了能够访问此页面,必须对此用户进行身份验证isAuthenticated(),但是,我还要检查表中 team_members中用户的角色 admin
所以我的问题是,最好的方法是什么?我应该在每个必须验证这种情况的控制器功能的开始时插入 if 吗?对此有更清洁的解决方案吗?

我试图创建

package com.sports.beans;

import org.springframework.stereotype.Component;

@Component("mySecurityService")
public class MySecurityService {

    public boolean hasPermission(String key) {
        return false;
    }
}

并将@PreAuthorize("@mySecurityService.hasPermission('special')")添加到控制器功能但它没有工作。编辑:方法mySecurityService.hasPermission(...)未被调用

这是我的spring-security.xml

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


<global-method-security pre-post-annotations="enabled" />
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/user**" access="hasRole('ROLE_USER')" />
    <intercept-url pattern="/teams/**" access="isAuthenticated()" />

    <!-- access denied page -->
    <access-denied-handler error-page="/403" />
        <form-login login-page="/login" authentication-failure-url="/login?error"
            username-parameter="username" password-parameter="password" />
        <logout logout-success-url="/login?logout" />
        <!-- enable csrf protection -->
        <csrf />
    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="myUserDetailsService">
            <password-encoder hash="bcrypt"/>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="mySecurityService" class="com.sports.beans.MySecurityService" />

</beans:beans>  

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"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
         version="3.0">
  <display-name>Sports</display-name>

<!-- Spring MVC -->  


    <servlet>  
        <servlet-name>mvc-dispatcher</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>mvc-dispatcher</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  

    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
            /WEB-INF/spring-database.xml,  
            /WEB-INF/spring-security.xml  
        </param-value>  

    </context-param>  

 <!-- Spring Security -->

 <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>


    <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  </web-app>

spring-database.xml

<?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:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:sec="http://www.springframework.org/schema/security" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
                            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                             http://www.springframework.org/schema/aop 
                             http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
                             http://www.springframework.org/schema/tx 
                             http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                             http://www.springframework.org/schema/security
                             http://www.springframework.org/schema/security/spring-security-3.2.xsd
                             http://www.springframework.org/schema/context
                             http://www.springframework.org/schema/context/spring-context.xsd">



    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test_sports"/>
        <property name="username" value="root"/>
        <property name="password" value="lol123" /> 
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <property name="dataSource" ref="dataSource"/>
        <property name="annotatedClasses">
           <list>
                <value>com.sports.models.User</value>
                <value>com.sports.models.UserRole</value>
                <value>com.sports.models.Team</value>
                <value>com.sports.models.TeamMember</value>
           </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <bean id="userDao" class="com.sports.dao.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

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

    <bean id="myUserDetailsService" class="com.sports.service.MyUserDetailsService">
        <property name="userDao" ref="userDao"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="userServicePointCut" expression="execution(* com.sports.service.*Service.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut"/>
    </aop:config>
</beans>

mvc-dispatcher-servlet.xml

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

    <context:component-scan base-package="com.sports.*"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

1 个答案:

答案 0 :(得分:0)

为了让@PreAuthorize影响代码,您需要确保enable method security。例如:

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

常见问题是用户将在其控制器上定义安全注释,在父上下文中定义global-method-security元素。这不起作用。

global-method-security元素必须在与您尝试保护的资源相同的Spring Context中定义。因此,例如,如果根ApplicationContext定义了您尝试保护的服务bean,那么它还应该引用包含global-method-security的配置。

对于您的示例,这可能意味着应该通过web.xml中的以下内容选择所有配置:

<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>  
        /WEB-INF/spring-database.xml,  
        /WEB-INF/spring-security.xml  
    </param-value>  
</context-param>