2012-07-10 66 views
6

我被困在這個問題很長一段時間。我想用@Secure來訪問控制添加到我的控制器ArticleController.java這樣的:Spring-Security如何在我的控制器上使用<global-method-security>?

@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返回一個JSON對象Articles但只有管理員可以閱讀它們。好吧,現在我配置Spring-Security來完成這項工作。

我使用Spring-ROO的security setup功能,以下提供配置生成:

在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,但沒有奏效。那麼也許控制器不在安全上下文的相同上下文中,所以我添加到以DispatcherServlet開頭的/spring/webmvc-config.xml,不起作用。

我也添加到另一個默認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會使它變得混亂嗎?

+0

[@Secured annotations在Autoproxy中無法在AspectJ模式下工作](http://stackoverflow.com/questions/11400503/secured-annotations-not-working-in-aspectj-mode-with-autoproxy) – axtavt 2012-07-10 14:02:19

+0

你爲什麼不想使用''?這是做這件事的標準方式。 – sourcedelica 2012-07-10 14:05:59

+0

@sourcedelica你是對的,我之所以使用roo是爲了方便,我不能在此花更多時間。但是像@ @ Async這樣的其他標籤也無法工作,所以我想到了一些可能會有人知道的配置錯誤。 – JerryCai 2012-07-10 14:21:30

回答

10

正如@Luke Taylor在評論中所建議的,標記<sec:global-method-security/>需要在dispatcher-servlet.xml(本例中爲webmvc-config.xml)文件中定義。並且沒有必要具有屬性mode="aspectj"

謝謝。

+2

謝謝SOOOOOO很多!現在我已經把頭撞在這堵特殊的磚牆上了。爲什麼選擇Spring爲什麼你需要把安全相關的配置放在你的調度器 - serlvet配置中,而不是在你的安全配置中?我相信肯定有一個很好的理由.... – 2013-10-17 08:07:58

相關問題