SpringBoot + Shiro前后端分离权限
shiro验证通过后的信息保存在session中,而ajax每次传的都是不同的sessionid,所以主要的区别就是需要修改shiro获取sessionid的方式。这里使用的是登录后将后台的sessionid传到前端然后存放到cookie(这个存放的地方视情况而定),然后每次请求后端时在Header中携带此信息,这里起名为Authorization
shiro中默认获取Sessionid的类是 DefaultWebSessionManager 所以需要重写此类
importorg.apache.commons.lang3.StringUtils;
importorg.apache.shiro.web.servlet.ShiroHttpServletRequest;
importorg.apache.shiro.web.session.mgt.DefaultWebSessionManager;
importorg.apache.shiro.web.util.WebUtils;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjava.io.Serializable;
publicclassPowerShiroSessionManagerextendsDefaultWebSessionManager{
/**
*获取请求头中key为“Authorization”的value==sessionId
*/
privatestaticfinalStringAUTHORIZATION="Authorization";
privatestaticfinalStringREFERENCED_SESSION_ID_SOURCE="cookie";
@Override
protectedSerializablegetSessionId(ServletRequestrequest,ServletResponseresponse){
//TODOAuto-generatedmethodstub
StringsessionId=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);
returnsessionId;
}
returnsuper.getSessionId(request,response);
}
}
然后在配置中配置此类
@Bean
publicSessionManagersessionManager(){
PowerShiroSessionManagershiroSessionManager=newPowerShiroSessionManager();
returnshiroSessionManager;
}
@Bean
publicSecurityManagersecurityManager(){
DefaultWebSecurityManagersecurityManager=newDefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
//自定义session管理
securityManager.setSessionManager(sessionManager());
returnsecurityManager;
}
然后修改前端,这里前端使用的时Vue.js,登录成功后将SessionId保存到cookie中,并将请求中携带头信息
util.setCookie("SESSIONID",data.data.sessionId,1);
axios.defaults.headers.common['Authorization']=util.getCookie("SESSIONID");
这样后端就能根据这个sessionid判断出用户是否通过认证
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。