ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring Security注解@PreAuthorize与AOP切面执行顺序

2022-01-26 23:59:48  阅读:227  来源: 互联网

标签:顺序 PreAuthorize Spring public AOP BeforeController before


引入Spring Security后,在Controller的方法中会出现Spring Security的方法注解与AOP同时存在的问题,这是就会设计顺序问题

@Controller
public class HelloController{
	@RequestMapping(value = "/hello")
	@BeforeController
	@PreAuthorize("validate(#user)")
	public void hello(@RequestParam("user) String user) {
		// 业务代码 
	}
}

上述Controller中@BeforeController是一个业务AOP,@PreAuthorize是来授权校验user。按照业务逻辑,执行顺序应该是如下:

Created with Raphaël 2.3.0 request @PreAuthorize @BeforeController 业务代码

但实际是@BeforeController@PreAuthorize之前。
其实@PreAuthorize也是依赖于AOP实现,当多个AOP在一个方法上时就会有顺序问题。在Aop中指定顺序的方法有:

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BeforeController {

}
  • 1、@Order注解
    @Aspect
    @Component
    @Order(0)
    public class BeforeControllerAction {
        @Before("@annotation(org.numb.web.aop.BeforeController)")
        public void before(final JoinPoint joinPoint) {
            // before切面业务代码
        }
    }
    
    @Order注解里面的值是一个整数,数值越大优先级越低,默认是Integer.MIN_VALUE,即最低优先级。
  • 2、实现org.springframework.core.Ordered接口
    @Aspect
    @Component
    public class BeforeControllerAction implements Ordered {
        @Before("@annotation(org.numb.web.aop.BeforeController)")
        public void before(final JoinPoint joinPoint) {
            // before切面业务代码
        }
    
    
        @Override
        public int getOrder() {
            return 0;
        }
    }
    
  • 3、通过配置文件配置顺序
    <aop:config expose-proxy="true">
        <aop:pointcut id="beforeController" expression="@annotation(org.numb.web.aop.BeforeController)"/>
        <aop:aspect ref="beforeControllerAction" id="beforeControllerAction">
            <aop:before method="before" pointcut-ref="beforeController"/>
        </aop:aspect>
    </aop:config>
    

而Spring Security的执行顺序本质上也是由AOP决定,可以通过指定order的方式确定:

@EnableGlobalMethodSecurity(order = 0)

查看源码可见

public @interface EnableGlobalMethodSecurity {
...
	/**
	 * Indicate the ordering of the execution of the security advisor when multiple
	 * advices are applied at a specific joinpoint. The default is
	 * {@link Ordered#LOWEST_PRECEDENCE}.
	 * @return the order the security advisor should be applied
	 */
	int order() default Ordered.LOWEST_PRECEDENCE;

}

标签:顺序,PreAuthorize,Spring,public,AOP,BeforeController,before
来源: https://blog.csdn.net/Numb_ZL/article/details/122640442

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有