现在的位置: 首页 > 编程语言 > 正文

SpringBoot+Shiro前后端分离权限

2020年02月13日 编程语言 ⁄ 共 2149字 ⁄ 字号 评论关闭

shiro 验证通过后的信息保存在session 中,而ajax 每次传的都是不同的sessionid ,所以主要的区别就是需要修改shiro获取sessionid的方式。这里使用的是登录后将后台的sessionid 传到前端然后存放到 cookie(这个存放的地方视情况而定),然后每次请求后端时在Header中携带此信息,这里起名为Authorization

shiro 中 默认获取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判断出用户是否通过认证

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: SpringBoot + Shiro前后端分离权限

以上就上有关SpringBoot+Shiro前后端分离权限的相关介绍,要了解更多SpringBoot,Shiro前后端分离权限,SpringBoot前后端分离,Shiro前后端分离内容请登录学步园。

抱歉!评论已关闭.