记录一下工作中遇到的问题,用的shiro进行登录校验,默认取的是浏览器cookies,后面对接第三方因为某种原因,后面修改为通过url参数进行校验。
自定义一个session 管理器需要继承DefaultWebSessionManager
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.util.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Map;
/**
* @author DaGangCai
* @Date 2020/9/27-9:22
*/
public class ShiroSessionManager extends DefaultWebSessionManager {
private static final String AUTHORIZATION = "userToken";
private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
public ShiroSessionManager() {
//重写构造器
super();
this.setDeleteInvalidSessions(true);
}
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
Map<String, String[]> map = request.getParameterMap();
String token = StringUtils.arrayToCommaDelimitedString(map.get(AUTHORIZATION));
// 如果请求参数中存在token 则从请求头中获取token
if (!StringUtils.isEmpty(token)) {
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return token;
} else {
// 否则按默认规则从cookie取token
return super.getSessionId(request, response);
}
}
}
权限配置工厂类(ShiroConfiguration),这里获取session做如下修改
@Bean
public DefaultWebSessionManager sessionManager(RedisTemplate redisTemplate) {
// 原来是这样的,改成ShiroSessionManager sessionManager = new ShiroSessionManager();
// DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
ShiroSessionManager sessionManager = new ShiroSessionManager();
//设置sessionDao对session查询,在查询在线用户service中用到了
sessionManager.setSessionDAO(redisSessionDao(redisTemplate));
//设置在cookie中的sessionId名称
sessionManager.setSessionIdCookie("这里自定义,不写也行");
sessionManager.setSessionValidationSchedulerEnabled(true);
sessionManager.setSessionIdCookieEnabled(true);
return sessionManager;
}