使用方法级安全性处理AccessDenied

时间:2011-10-27 13:21:44

标签: spring spring-security

我有一个使用弹簧安全保护的方法如下:

@PreAuthorize("hasRole('add_user')")
public void addUser(User user) ;

如果没有enoguh权限的用户试图调用它 ,抛出accessDenied异常:

org.springframework.security.access.AccessDeniedException: Access is denied

这是预期的,但问题是,为什么定义的 access-denied-handler

security.xml配置文件中的

无法正常工作

<access-denied-handler error-page="accessDenied"/>

我的意思是不工作当用户在尝试按下按钮时没有足够的权限addUser将调用服务addUser(用户只能访问该权限)具有此权限抛出了AccessDenied Exception并且这是所需的行为,但是用户没有被重定向到xml中配置的访问被拒绝的异常。

当抛出此异常时,用户是否应该自动重定向到访问被拒绝的页面,或者我必须在代码中明确定义此类行为?

请告知。

我正在使用 Spring Security 3.0.5 JSF 2.1 ICEFaces 2

更新: applicationSecurity.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"
    xmlns:util="http://www.springframework.org/schema/util"
    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.0.4.xsd
          http://www.springframework.org/schema/util
          http://www.springframework.org/schema/util/spring-util-3.1.xsd">


        <!-- Enable @pre, @post spring security method level annotations -->
        <global-method-security pre-post-annotations="enabled" />   


        <http use-expressions="true"  auto-config="true" access-denied-page="/accessDenied">

     <session-management session-fixation-protection="none"/>

        <remember-me  token-validity-seconds="1209600"/>


        <intercept-url pattern="/accessDenied" access="permitAll"/>        
        <intercept-url pattern="/login" access="permitAll"/>
        <intercept-url pattern="/j_spring_security_check" access="permitAll" />


        <intercept-url pattern="/faces/javax.faces.resource/**" access="permitAll" />
        <intercept-url pattern="/xmlhttp/**" access="permitAll" />
        <intercept-url pattern="/resources/**" access="permitAll" />        
        <intercept-url pattern="/scripts/**" access="permitAll" />
        <intercept-url pattern="/images/**" access="permitAll" />
        <intercept-url pattern="/css/**" access="permitAll" />


        <!-- All pages requires authentication (not anonymous user) -->

        <intercept-url pattern="/**" access="isAuthenticated()" />
        <intercept-url pattern="/faces/**" access="isAuthenticated()" />


        <form-login default-target-url="/"   
        always-use-default-target="true"            
            login-processing-url="/j_spring_security_check"         
            login-page="/login"
            authentication-failure-url="/login?login_error=1"                                                               
        />

        <logout logout-url="/logout" logout-success-url="/login" />     
    </http>

    <authentication-manager alias="authenticationManager">          
      <authentication-provider user-service-ref="userDetailsServiceImpl"/>    
    </authentication-manager>


    </beans:beans>

UPDATE 2 :在异常之前进行调试:

DEBUG [http-bio-8080-exec-1] (PrePostAnnotationSecurityMetadataSource.java:93) - @org.springframework.security.access.prepost.PreAuthorize(value=hasRole('add_user')) found on specific method: public void com.myapp.service.impl.UserServiceImpl.addUser(com.myapp.domain.User) throws java.lang.Exception,org.springframework.security.access.AccessDeniedException
DEBUG [http-bio-8080-exec-1] (DelegatingMethodSecurityMetadataSource.java:66) - Adding security method [CacheKey[com.myapp.service.impl.UserServiceImpl; public abstract void com.myapp.service.UserService.addUser(com.myapp.domain.User) throws java.lang.Exception,org.springframework.security.access.AccessDeniedException]] with attributes [[authorize: 'hasRole('add_user')', filter: 'null', filterTarget: 'null']]
DEBUG [http-bio-8080-exec-1] (AbstractSecurityInterceptor.java:191) - Secure object: ReflectiveMethodInvocation: public abstract void com.myapp.service.UserService.addUser(com.myapp.domain.User) throws java.lang.Exception,org.springframework.security.access.AccessDeniedException; target is of class [com.myapp.service.impl.UserServiceImpl]; Attributes: [[authorize: 'hasRole('add_user')', filter: 'null', filterTarget: 'null']]
DEBUG [http-bio-8080-exec-1] (AbstractSecurityInterceptor.java:292) - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@c650d918: Principal: org.springframework.security.core.userdetails.User@db344023: Username: user@mycomp.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: access_viewUsers; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: E6BBAC0CD4499B1455227DC6035CC882; Granted Authorities: access_viewUsers
DEBUG [http-bio-8080-exec-1] (AffirmativeBased.java:53) - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter@1d1e082e, returned: -1
DEBUG [http-bio-8080-exec-1] (AffirmativeBased.java:53) - Voter: org.springframework.security.access.vote.RoleVoter@1eab12f1, returned: 0
DEBUG [http-bio-8080-exec-1] (AffirmativeBased.java:53) - Voter: org.springframework.security.access.vote.AuthenticatedVoter@71689bf1, returned: 0

3 个答案:

答案 0 :(得分:4)

根据spring Security文档,该元素的access-denied-page属性的用户已在Spring 3.0及更高版本中弃用。

我们在应用中执行以下操作:

  1. 通过扩展Sp​​ring Security框架的AccessDeniedHandlerImpl来创建自定义访问被拒绝处理程序。
  2. 调用setErrorPage方法,传入将显示拒绝访问页面的控制器名称
  3. 在我们的案例中,我们将用户的帐户锁定在自定义处理程序中 - 没有任何理由让任何用户获得访问被拒绝的异常,除非他们正在做他们不应该做的事情。我们还记录了他们试图访问的内容等。
  4. 在处理程序的末尾调用super.handle(_request, _response, _exception);。 Spring会将控制权转发给上面#2中列出的控制器。

    public class AccessDeniedHandlerApp extends AccessDeniedHandlerImpl {
        private static Logger logger = Logger.getLogger(AccessDeniedHandlerApp.class);
    
        private static final String LOG_TEMPLATE = "AccessDeniedHandlerApp:  User attempted to access a resource for which they do not have permission.  User %s attempted to access %s";
    
         @Override
         public void handle(HttpServletRequest _request, HttpServletResponse _response, AccessDeniedException _exception) throws IOException, ServletException {
             setErrorPage("/securityAccessDenied");  // this is a standard Spring MVC Controller
    
             // any time a user tries to access a part of the application that they do not have rights to lock their account
             <custom code to lock the account>
             super.handle(_request, _response, _exception);
    }
    

    }

  5. 这是我的XML:AccessDeniedHandlerApp扩展'AccessDeniedHandlerImpl`

    <http auto-config='true'>
        <intercept-url pattern="/views/**" access="ROLE_USER" />
        <form-login login-page="/Login.jsp" authentication-success-handler-ref="loginSuccessFilter"
                    authentication-failure-handler-ref="loginFailureFilter" />
        <logout logout-success-url="/home" />
        <access-denied-handler ref="customAccessDeniedHandler"/>
    </http>
    
    <beans:bean id="customAccessDeniedHandler" class="org.demo.security.AccessDeniedHandlerApp"/>
    

    这是我的拒绝访问控制器 - 我应该早点发布 - 抱歉。为了让访问被拒绝的页面出现,我不得不使用重定向:

    @Controller
    public class AccessDeniedController {
        private static Logger logger = Logger.getLogger(AccessDeniedController.class);
    
        @RequestMapping(value = "/securityAccessDenied")
        public String processAccessDeniedException(){
            logger.info("Access Denied Handler");
            return "redirect:/securityAccessDeniedView";
        }
    
        @RequestMapping(value = "/securityAccessDeniedView")
        public String displayAccessDeniedView(){
            logger.info("Access Denied View");
            return "/SecurityAccessDenied";
        }
    

    请告诉我,如果这不能解决它,我将继续挖掘 - 我只是在本地再次测试它,这应该可以解决问题。     }

答案 1 :(得分:1)

我自己也遇到了同样的问题,并发布了另一个与同一问题有关的问题。经过几个小时的挖掘,我终于找到了解决问题的方法。我知道这个问题是2年多了,但我想我会用信息更新它,以防它对别人有价值。

简而言之,我注意到SimpleMappingExceptionResolver正在处理异常并使用默认映射解析它。因此,没有任何例外可以将堆栈冒泡到ExceptionTranslationFilter,这会重定向到access-denied-handler

有关详细信息,请参阅Spring Security ignoring access-denied-handler with Method Level Security

答案 2 :(得分:0)

当用户无权访问资源时,Spring Security会重定向到访问被拒绝页面。这是在用户通过身份验证但没有允许的角色时。

但是当问题不是授权,而是身份验证时,Spring Security会重定向到登录页面(让用户自己验证身份),而不是访问被拒绝页面。

如果您在规则中检查“isAuthenticated()”规则,则不会将您重定向到拒绝访问页面,而是重定向到登录页面。

希望它有所帮助。