shiro 验证通过后的信息保存在session 中,而ajax 每次传的都是不同的sessionid ,所以主要的区别就是需要修改shiro获取sessionid的方式。
这里使用的是登录后将后台的sessionid 传到前端然后存放到 cookie(这个存放的地方视情况而定),然后每次请求后端时在Header中携带此信息,这里起名为Authorizationshiro 中 默认获取Sessionid的类是 DefaultWebSessionManager 所以需要重写此类
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
public class PowerShiroSessionManager extends DefaultWebSessionManager {
/**
* 获取请求头中key为“Authorization”的value == sessionId
*/
private static final String AUTHORIZATION ="Authorization";
private static final String REFERENCED_SESSION_ID_SOURCE = "cookie";
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
// TODO Auto-generated method stub
String sessionId = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
System.out.println(sessionId);
if (StringUtils.isNotEmpty(sessionId)) {
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return sessionId;
}
return super.getSessionId(request, response);
}
}
|
然后在配置中配置此类
@Bean
public SessionManager sessionManager() {
PowerShiroSessionManager shiroSessionManager = new PowerShiroSessionManager();
return shiroSessionManager;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
//自定义session管理
securityManager.setSessionManager(sessionManager());
return securityManager;
}
|
然后修改前端,这里前端使用的时Vue.js,登录成功后将SessionId保存到cookie中,并将请求中携带头信息
util.setCookie("SESSIONID",data.data.sessionId,1);
axios.defaults.headers.common['Authorization'] = util.getCookie("SESSIONID");
|
这样后端就能根据这个sessionid判断出用户是否通过认证
|