67,513
社区成员
发帖
与我相关
我的任务
分享
@Component
@Aspect
public class SecurityAspect {
private static final Logger logger = LoggerFactory.getLogger(SecurityAspect.class);
private TokenManager tokenManager;
@Resource(name = "tokenManager")
public void setTokenManager(TokenManager tokenManager) {
this.tokenManager = tokenManager;
}
@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public Object execute(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
logger.debug("methodSignature : " + methodSignature);
Method method = methodSignature.getMethod();
logger.debug("Method : " + method.getName() + " : "
+ method.isAnnotationPresent(IgnoreSecurity.class));
if (method.isAnnotationPresent(IgnoreSecurity.class)) {
return pjp.proceed();
}
String token = WebContext.getRequest().getHeader(
Constants.DEFAULT_TOKEN_NAME);
if (!tokenManager.checkToken(token)) {
String message = String.format("token [%s] is invalid", token);
logger.debug("message : " + message);
throw new TokenException(message);
}
return pjp.proceed();
}
}
<!-- token 检查 -->
<bean id="securityAspect" class="com.api.work.base.SecurityAspect">
<property name="tokenManager" ref="tokenManager" />
<property name="tokenName" value="X-Token" />
</bean>
<bean id="tokenManager" class="com.api.work.base.DefaultTokenManager" />
<aop:config>
<aop:aspect ref="securityAspect">
<aop:around method="executeOne"
pointcut="execution(* org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(..))"/>
</aop:aspect>
</aop:config>
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
即可