有如下需求:在没有权限管理的情况下阻挡普通用户的接口请求,可以做自定义验证来验证接口权限。
1、拦截器
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* 未登录拦截器
*/
public class BusinessLoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 获取HttpSession对象
HttpSession httpSession = request.getSession();
// 获取我们登录后存在session中的用户信息,如果为空,表示session已经过期
Object sessionAttribute = httpSession.getAttribute(CommonConstant.PURCHASE_SHOPKEEPER);
// 状态码2000 表示没登录
if (null == sessionAttribute) {
throw new LoginToException(ReturnCode.NO_LOGIN.getCode(), CommonConstant.NO_LOGIN);
}
String storeId = (String) WebUtils.getSessionAttribute(request, CommonConstant.STORE_ID);
// 不是管理员必须有店铺id
if (!isAdmin(request) && storeId == null) {
//非法请求,未选择店铺!
returnJson(response, ReturnCode.ILLEGAL_REQUEST_NO_STORE_SELECTED);
return false;
}
// 判断是不是管理员 使用自定义注解
if (handler instanceof HandlerMethod) {
//自定义注解
CheckAdmin annotation = AnnotationUtils.findAnnotation(((HandlerMethod) handler).getMethod(), CheckAdmin.class);
if (annotation != null) {
if (!isAdmin(request)) {
//没有权限
returnJson(response, ReturnCode.USER_NO_PERMISSION_LOCKED_ERROR);
return false;
}
}
}
//已经登录
return true;
}
/**
* @Description: 判断是不是管理员
* @Param [request]
* @Return: boolean
**/
private boolean isAdmin(HttpServletRequest request) {
BusinessLoginRequest businessLoginRequest = (BusinessLoginRequest) request.getSession().getAttribute(CommonConstant.PURCHASE_SHOPKEEPER);
return businessLoginRequest.getAccount().equals(CommonConstant.ADMIN);
}
/**
* @Description: json异常信息
* @Param [response, result]
* @Return: void
**/
private void returnJson(HttpServletResponse response, ReturnCode result) throws IOException {
String json = JSON.toJSONString(Result.Error(result));
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().println(json);
}
}
2、自定义注解
import java.lang.annotation.*;
/**
* @Description: 判断是否admin账号
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckAdmin {
}