对于前面已经实现的功能中,对于项目存在一定的安全隐患
比如在没有登录的情况下可以直接通过 localhost:8081/community/user/setting 访问只有登录之后才允许访问的页面。
下面将通过自定义注解和拦截器搭配的方式实现没登录时不能访问一些请求的功能。
@Target用于描述该注解可以作用的目标类型
@Retention用于描述该注解被保留的时间
@Document用于描述该注解是否可以生成到文档里
如果某个类使用@Inherited修饰,则该类的子类将自动使用@Inherited修饰。
- 自定义注解
package com.wjiangquan.community.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author weijiangquan
* @date 2022/10/7 -2:04
* @Description
*/
@Target(ElementType.METHOD) //在方法中起作用
@Retention(RetentionPolicy.RUNTIME) //运行时起作用
public @interface LoginRequired {
}
- 书写拦截器,确定需要拦截的请求
package com.wjiangquan.community.controller.interceptor;
import com.wjiangquan.community.annotation.LoginRequired;
import com.wjiangquan.community.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
* @author weijiangquan
* @date 2022/10/7 -2:07
* @Description 用户避免用户没有访问只有登录之后才可以访问的请求 比如 /user/setting
*/
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LoginRequiredInterceptor.class);
@Autowired
private HostHolder hostHolder;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.debug("handler"+handler);
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
LoginRequired annotation = method.getAnnotation(LoginRequired.class);
if (annotation != null && hostHolder.getUser() == null) {
response.sendRedirect(request.getContextPath() + "/login");
return false;
}
}
return true;
}
}
- 在需要拦截的请求上加上注解,通过注解的方式获取需要拦截的请求
当页面中通过路径直接访问时,直接重定向到登录界面
在本项目中目前需要拦截的请求为 下面中的setting 和 上传图片,后面可以根据实际的需要进行添加
在本项目中目前需要拦截的请求为 下面中的setting 和 上传图片,后面可以根据实际的需要进行添加