首先,在WebMvcConfigurerAdapter配置拦截器SessionHandlerInterceptor:SessionHandlerInterceptor
package com.tal.blockchain.token.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* WebConfig
*
* @author liyingkong.
*/
@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {
// @Autowired
// private LoginInterceptor loginInterceptor;
// @Autowired
// SessionHandlerInterceptor sessionHandlerInterceptor;
public WebConfig() {
super();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
SessionHandlerInterceptor sessionHandlerInterceptor = new SessionHandlerInterceptor();
registry.addInterceptor(sessionHandlerInterceptor).addPathPatterns("/**");
super.addInterceptors(registry);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*/*").allowedMethods("*")
.maxAge(120);
}
}
拦截器SessionHandlerInterceptor:
package com.tal.blockchain.token.config;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tal.blockchain.token.common.CommonResponse;
import com.tal.blockchain.token.common.constant.BaseConstant;
import com.tal.blockchain.token.common.enums.ResponseEnum;
import com.tal.blockchain.token.common.enums.UserTypeEnum;
import com.tal.blockchain.token.dao.ITokenManagerDAO;
import com.tal.blockchain.token.dao.entity.TokenManagerEntity;
import com.tal.blockchain.token.redis.RedisDAO;
/**
* Session相关的检查
*
* @author gaohaigang
*
*/
public class SessionHandlerInterceptor implements HandlerInterceptor {
private Long managerSessionValidTime = BaseConstant.MANAGER_SESSION_VALID_TIME;
private Long appManagerSessionValidTime = BaseConstant.APP_MANAGER_SESSION_VALID_TIME;
private Long userSessionValidTime = BaseConstant.USER_SESSION_VALID_TIME;
@Autowired
private RedisDAO redisDAO;
@Autowired
private ITokenManagerDAO iTokenManagerDao;
// public SessionHandlerInterceptor(RedisDAO redisDAO, ITokenManagerDAO iTokenManagerDao,
// Long managerSessionValidTime, Long employeeSessionValidTime, Long teacherSessionValidTime) {
// this.redisDAO = redisDAO;
// this.iTokenManagerDao = iTokenManagerDao;
// this.managerSessionValidTime = managerSessionValidTime;
// this.employeeSessionValidTime = employeeSessionValidTime;
// this.teacherSessionValidTime = teacherSessionValidTime;
// }
/**
* Session等相关验证
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 允许跨域请求
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
String url = request.getRequestURI();
// 不需要做验证的请求getByVcode
if (url.contains("api/admin/login") || url.contains("api/admin/registAdmin")
|| url.contains("api/admin/registManager") || url.contains("api/v1/employee/export")
|| url.contains("api/v1/employee/importBatchTransfer") || url.contains("/error")
|| url.contains("api/v1/transfer/getBatchTransferImportTemplate")
|| url.contains("springboot/ok")
|| url.contains("api/v1/transfer/getBatchTransferImportTemplate")) {
response.setContentType("application/json; charset=utf-8");
return true;
}
Cookie[] cookies = request.getCookies();
// Cookies验证码
if (cookies == null || cookies.length == 0) {
// 判断Session
writeData(response);
return false;
}
String sessionId = null;
String sessionData = null;
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
if (name.equals("sessionId")) {
sessionId = cookies[i].getValue();
}
if (name.equals("sessionData")) {
sessionData = cookies[i].getValue();
}
}
// Session不存在
if (sessionId == null || sessionData == null) {
writeData(response);
return false;
}
String userId = redisDAO.get(sessionId).toString();
String userType = redisDAO.get(sessionData).toString();
// Redis获取不到
if (userId == null || userType == null) {
writeData(response);
return false;
}
// 根据用户的操作去判断
// 管理员
long sessionValidTime = 0;
if (userType.equals(UserTypeEnum.MANAGER.getCode())) {
TokenManagerEntity manager = iTokenManagerDao.readById(Integer.valueOf(userId));
if (manager == null) {
writeData(response);
return false;
}
sessionValidTime = managerSessionValidTime;
} else if (userType.equals(UserTypeEnum.APP_MANAGER.getCode())) {
TokenManagerEntity manager = iTokenManagerDao.readById(Integer.valueOf(userId));
if (manager == null) {
writeData(response);
return false;
}
sessionValidTime = appManagerSessionValidTime;
} else if (userType.equals(UserTypeEnum.USER.getCode())) {
TokenManagerEntity manager = iTokenManagerDao.readById(Integer.valueOf(userId));
if (manager == null) {
writeData(response);
return false;
}
sessionValidTime = userSessionValidTime;
}
// 验证通过重新设置过期时间(单位:分钟)
redisDAO.expire(sessionId, sessionValidTime);
redisDAO.expire(sessionData, sessionValidTime);
return true;
}
/**
* 返回数据
*
* @param response
*/
private void writeData(HttpServletResponse response) {
try {
PrintWriter writer = response.getWriter();
CommonResponse com = CommonResponse.fail("Login Needed");
com.setStatus(ResponseEnum.PARAMETER_SESSION_NEEDED.getCode());
writer.print(JSONObject.toJSONString(com, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat));
writer.close();
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
}