spring-mvc - <global-method-security> 如何通过 Spring-Security 在我的 Controller 上工作?

标签 spring-mvc spring-security spring-roo

我被这个问题困了很长时间。我想用@Secure将访问控制添加到我的 Controller ArticleController.java像这样:

@RequestMapping(headers = "Accept=application/json")
@ResponseBody
@Secured("ROLE_ADMIN")
public ResponseEntity<String> listJson() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=utf-8");
    List<Article> result = Article.findAllArticles();
    return new ResponseEntity<String>(Article.toJsonArray(result), headers, HttpStatus.OK);
}

listJson 为 Articles 返回一个 Json 对象但只有管理员可以阅读它们。好的,现在我配置 Spring-Security 来完成这项工作。

我用 security setup Spring-ROO的功能,生成如下配置:

在 web.xml 中:
     <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
     </context-param>
....
    <servlet>
        <servlet-name>BabyPortal</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/spring/webmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

spring/webmvc-config.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
    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.1.xsd                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd                 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd      http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <tx:annotation-driven/>
    <!-- The controllers are autodetected POJOs labeled with the @Controller 
        annotation. -->
    <context:component-scan base-package="com.tongxinyuan.babyportal"
        use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller"
            type="annotation" />
    </context:component-scan>

    <!-- Turns on support for mapping requests to Spring MVC @Controller methods 
        Also registers default Formatters and Validators for use across all @Controllers -->
    <mvc:annotation-driven conversion-service="applicationConversionService" />


    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources -->
    <mvc:resources location="/, classpath:/META-INF/web-resources/"
        mapping="/resources/**" />

    <!-- Allows for mapping the DispatcherServlet to "/" by forwarding static 
        resource requests to the container's default Servlet -->
    <mvc:default-servlet-handler />

    <!-- Register "global" interceptor beans to apply to all registered HandlerMappings -->
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" />
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
            p:paramName="lang" />
    </mvc:interceptors>

    <!-- Selects a static view for rendering without the need for an explicit 
        controller -->
    <mvc:view-controller path="/login" />
    <mvc:view-controller path="/" view-name="index" />
    <mvc:view-controller path="/uncaughtException" />
    <mvc:view-controller path="/resourceNotFound" />
    <mvc:view-controller path="/dataAccessFailure" />

    <!-- Resolves localized messages*.properties and application.properties 
        files in the application to allow for internationalization. The messages*.properties 
        files translate Roo generated messages which are part of the admin interface, 
        the application.properties resource bundle localizes all application specific 
        messages such as entity names and menu items. -->
    <bean
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
        id="messageSource" p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application"
        p:fallbackToSystemLocale="false" />

    <!-- Store preferred language configuration in a cookie -->
    <bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver"
        id="localeResolver" p:cookieName="locale" />

    <!-- Resolves localized <theme_name>.properties files in the classpath to 
        allow for theme support -->
    <bean
        class="org.springframework.ui.context.support.ResourceBundleThemeSource"
        id="themeSource" />

    <!-- Store preferred theme configuration in a cookie -->
    <bean class="org.springframework.web.servlet.theme.CookieThemeResolver"
        id="themeResolver" p:cookieName="theme" p:defaultThemeName="standard" />

    <!-- This bean resolves specific types of exceptions to corresponding logical 
        - view names for error views. The default behaviour of DispatcherServlet 
        - is to propagate all exceptions to the servlet container: this will happen 
        - here with all other types of exceptions. -->
    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"
        p:defaultErrorView="uncaughtException">
        <property name="exceptionMappings">
            <props>
                <prop key=".DataAccessException">dataAccessFailure</prop>
                <prop key=".NoSuchRequestHandlingMethodException">resourceNotFound</prop>
                <prop key=".TypeMismatchException">resourceNotFound</prop>
                <prop key=".MissingServletRequestParameterException">resourceNotFound</prop>
            </props>
        </property>
    </bean>

    <!-- Enable this for integration of file upload functionality -->
    <bean
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
        id="multipartResolver" />
    <bean
        class="com.tongxinyuan.babyportal.controller.ApplicationConversionServiceFactoryBean"
        id="applicationConversionService" />
    <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"
        id="tilesViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.tiles2.TilesView" />
    </bean>
    <bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"
        id="tilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/layouts/layouts.xml</value>
                <!-- Scan views directory for Tiles configurations -->
                <value>/WEB-INF/views/**/views.xml</value>
            </list>
        </property>
    </bean>

    <security:global-method-security mode="aspectj" secured-annotations="enabled" pre-post-annotations="enabled"/>

</beans>

/spring/applicationContext-security.xml :
<?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.1.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    <!-- HTTP security configurations -->
    <http auto-config="true" use-expressions="true">
        <form-login login-processing-url="/resources/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t" />
        <logout logout-url="/resources/j_spring_security_logout" />
        <!-- Configure these elements to secure URIs in your application -->
        <intercept-url pattern="/choices/**" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/member/**" access="isAuthenticated()" />
        <intercept-url pattern="/resources/**" access="permitAll" />
        <intercept-url pattern="/*.html" access="hasRole('ROLE_ADMIN')" />
    </http>
    <!-- Configure Authentication mechanism -->
    <authentication-manager alias="authenticationManager">
        <authentication-provider>
            <user-service>
                <user name="admin" password="admin" authorities="ROLE_ADMIN" />
                <user name="user" password="user" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

首先,我尝试添加 <global-method-security mode="aspectj" secured-annotations="enabled" pre-post-annotations="enabled"/>/spring/applicationContext-security.xml但没有用。那么也许 Controller 不在安全上下文的同一上下文中,所以我添加到 /spring/webmvc-config.xml从 DispatcherServlet 开始的,没有用。

我还添加了另一个默认 applicationContext.xml ,也没有用。我不知道如何配置<global-method-security>这可以使方法安全工作。似乎我只使用了一个上下文,我错过了什么吗?希望这些信息足以说明这个问题。

PS:生成的URL方法效果很好:<intercept-url pattern="/*.html" access="hasRole('ROLE_ADMIN')" /> .

补充:
根据@LukeTaylor 的评论:我添加了 <global-method-security>webmvc-config.xml并删除了 mode="aspectj" ,确实有效,我也做了一些实验,还是有一些问题:

1)它有效但仅适用于ArticleController.java,ArticleController_Roo_Controller.aj中的@Secure标签仍然不起作用,这与“挥手”有关吗?
2) 你能解释一下为什么mode=aspectj把这里弄得一团糟?

最佳答案

正如@Luke Taylor 在评论中所建议的,标签 <sec:global-method-security/>需要在 dispatcher-servlet.xml(在本例中为 webmvc-config.xml)文件中定义。并且不需要属性mode="aspectj" .

谢谢。

关于spring-mvc - <global-method-security> 如何通过 Spring-Security 在我的 Controller 上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11414838/

相关文章:

grails - Spring Security重定向到登录时,端口8080来自哪里?如何更改为使用端口443?

spring - 为复合 PK 生成的空 ID

Spring Roo Jpa 设置失败,maven-eclipse-plugin 问题?

java - JSP 中的 Servlet

java - 即使依赖项由 Spring 容器管理后也无法 Autowiring 服务

java - Neo4J TokenStore Spring oauth2

spring - 将 Spring 依赖项注入(inject) JPA EntityListener

spring - Spring MVC 应用程序下的共享 HashMap

jquery - 在 jsp 中提交表单后,我想查看将哪些值发送到 Controller

java - 有什么方法可以在使用 spring 执行 rest api 之前验证 token