Prevent Method call without Exception using @PreAuthorize Annotation

前端 未结 3 1694
抹茶落季
抹茶落季 2021-01-01 02:25

We are using Spring Security 3. We have a custom implementation of PermissionEvaluator that has this complex algorithm to grant or deny access at method lev

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 02:44

    This is the code for the advice solution I implemented.

    This is the Aspect code:

    @Aspect
    public class AccessDeniedHaltPreventionAdvice {
    private final Log logger = LogFactory.getLog(AccessDeniedHaltPrevention.class);
    
    @Around("execution(@org.springframework.security.access.prepost.PreAuthorize * *(..))")
    public Object preventAccessDeniedHalting(ProceedingJoinPoint pjp) throws Throwable{
        Object retVal = null;
        try{
            retVal = pjp.proceed();
        }catch(AccessDeniedException ade){
            logger.debug("** Access Denied ** ");
        }catch(Throwable t){
            throw t;
        }
        return retVal;
    }
    

    }

    You may need to add a @Order annotation to ensure that the advice is able to catch the exception (usually a @Order(value=1) does the work). Also you'll need to add the aspectj autorproxy to the App context:

    
    

    You may also need to play around with the @Around parameters, In my case it was pretty simple as we are securing everything with PreAuthorize annotations.

    This the simplest way I could figure out. However, I strongly recommend people to use the solution suggested by Boris Kirzner.

    Hope this is helpful to someone.

提交回复
热议问题