package com.estate.expert.admin.interceptor; import com.estate.expert.common.auth.IgnoreAuth; import com.estate.expert.common.domain.Session; import com.estate.expert.admin.enums.BizResultCode; import com.estate.expert.admin.service.UserSessionService; import com.estate.expert.admin.utils.License; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; /** * 用于检查用户是否登录 * 会话拦截器 * * @Author code * @Date 2023/3/26 11:47 * @Version 1.0 */ @Component @Slf4j public class SsoSessionInterceptor implements HandlerInterceptor { private static final String REQUEST_ATTR_SESSION = "_session_"; private static final String REQUEST_KEY_TOKEN = "Authorization"; @Resource private UserSessionService userSessionService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws UnsupportedEncodingException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); // 检查License是否有效 try { License.validateLicense(); } catch (Exception e) { log.error("License验证失败,请求被拒绝: {}", request.getRequestURI()); // 使用BizResultCode的方式抛出异常,由全局异常处理器处理 throw e; } if (!(handler instanceof HandlerMethod)) { return true; } // log.info("request uri: {}", request.getRequestURI()); Session session = null; try { String token = request.getHeader(REQUEST_KEY_TOKEN).replace("Bearer ", ""); // log.info("token: {}", token); BizResultCode.NO_LOGIN_ERROR.check(StringUtils.isEmpty(token)); session = userSessionService.touchSession(token); } catch (Exception e) { IgnoreAuth noLogin = this.getIgnoreAuthAnnotation((HandlerMethod) handler); //如果未设置 @IgnoreAuth, 这返回未登录异常 BizResultCode.NO_LOGIN_ERROR.check(null == noLogin); } if (session == null) { session = new Session(); } request.setAttribute(REQUEST_ATTR_SESSION, session); return true; } private IgnoreAuth getIgnoreAuthAnnotation(HandlerMethod handlerMethod) { IgnoreAuth annotation = handlerMethod.getMethodAnnotation(IgnoreAuth.class); if (annotation == null) { annotation = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), IgnoreAuth.class); } return annotation; } }