@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RunAsSystem {
String role() default "ROLE_ADMIN";
}
@Aspect
@Order(1)
@Component
public class RunAsSystemAspect {
// 限定只在task中生效
@Around("@annotation(org.system.aop.annotation.RunAsSystem) && execution(public * org.system.task.*.*(..))")
public Object grantedSystemIdentification(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
RunAsSystem asSystem = methodSignature.getMethod().getAnnotation(RunAsSystem.class);
String role = asSystem.role();
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
"SYSTEM_SCHEDULER",
null,
// 給予指定的role
List.of(new SimpleGrantedAuthority(role))
)
);
try {
return joinPoint.proceed();
}finally {
// 無論執行結果,最後一定要清空Context
SecurityContextHolder.clearContext();
}
}
}
本篇文章出自《每天學Java直到今年結束》Day243,大家可以到我的網站上查看~
iThome鐵人賽