spring注解实现防盗链拦截

时间:2021-12-21 03:46:48

首先配置 applicationContext.xml, 添加

<!-- 启用 @AspectJ -->
<aop:aspectj-autoproxy />

新建Java工具类 util.java,获取referer信息

/**
* Title:工具类
* @author Victor
*/
public class util {
/**
* @description 获取referer,实现防盗链
* @param request
* @return String host
*/
public static String getReferer(HttpServletRequest request) {
String referer = request.getHeader("referer");
if(referer == null) {
return "nullReferer";
}
// 提取域名
try {
URL referUrl = new URL(referer);
String host = referUrl.getHost();
return host;
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "nullReferer";
}
}

新建 annotation 注解接口,实现自定义注解 AntitheftChain.java

/**
* Title:自定义注解
* Description: 标识是是否开启防盗链检查
* @author Victor
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AntitheftChain { }

了解更多关于 annotation 注解的知识,转至:https://www.cnblogs.com/victorlyw/articles/9969072.html

新建java类 SecurityAspect.java 实现安全检查

/**
* Title:安全检查切面(是否登录检查)
* @author Victor
*/
@Component
@Aspect
public class SecurityAspect {
@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public Object execute(ProceedingJoinPoint pjp) throws Throwable {
// 从切点上获取目标方法
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
Method method = methodSignature.getMethod();
// 目标方法是否开启防盗链检查
if (method.isAnnotationPresent(AntitheftChain.class)) {
// 获取请求域名
String getDomain = util.getReferer(WebContextUtil.getRequest());
if (getDomain == null || !getDomain.startsWith("localhost")) {
throw new domainException("没有认证域名");
}
}
}
}

新建 java类 domainException.java 异常处理

/**
* Title:盗链异常处理
* @author Victor
*/
public class domainException extends RuntimeException {
private static final long serialVersionUID = 1L; private String msg; public DomainException(String msg) {
super();
this.msg = msg;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
}
}

以上异常可以统一处理