java - Spring框架, Controller PreAuthorize中自定义函数

标签 java spring spring-mvc spring-security

我是 Spring 新手,我正在尝试学习开发一个简单的应用程序。

这是数据库的架构: /image/3H4jd.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');

当用户尝试编辑或访问要编辑其中一个团队的页面时,就会出现问题。这是我的 Controller 来执行此操作:

@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
所以我的问题是,最好的方法是什么?我是否应该在必须验证此条件的每个 Controller 函数的开头插入一个 if ?有没有更清洁的解决方案?

我尝试创建

package com.sports.beans;

import org.springframework.stereotype.Component;

@Component("mySecurityService")
public class MySecurityService {

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

并向 Controller 函数添加了 @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>

最佳答案

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

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

一个常见的问题是用户将在其 Controller 上定义安全注释以及父上下文中的 global-method-security 元素。这是行不通的。

global-method-security 元素必须在与您尝试保护的资源相同的 Spring 上下文中定义。例如,如果根 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>

关于java - Spring框架, Controller PreAuthorize中自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29330135/

相关文章:

java - 由 : java. lang.NoClassDefFoundError : Could not initialize class com. jayway.restassured.RestAssured 引起

java - 如何对 JTable 中找到的符号着色?

Java - 扩展简单的递归下降解析器

java - Spring Gateway RouteLocator 空指针异常

java - Spring boot 1.4.x 和自定义 CharsetProvider

Java:时间分辨率

java - 使用 JBoss 6 时,我的 pom.xml 中的 JTA jar 应该设置为什么?

java - Spring Webflow 2.3测试: How to mock @Autowired fields of a flow variable

Spring MVC : I set the default page but the spring always should me the configuration files do not find

java - 无法解析的依赖项 org.springframework.core.KotlinDetector.isKotlinReflectPresent()z