其他分享
首页 > 其他分享> > Spring Security注解@PreAuthorize与AOP切面执行顺序

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

作者:互联网

引入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 {

}

而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