Shiro之前后端分离时获取请求头Authorization中的token

重写DefaultWebSessionManager(org.apache.shiro.web.session.mgt.DefaultWebSessionManager)类中的getSessionId方法,代码如下:

public class CustomDefaultWebSessionManager extends DefaultWebSessionManager  {

/** 
* 获取session id
* 前后端分离将从请求头中获取jsesssionid
*/
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
// 从请求头中获取token
String token = WebUtils.toHttp(request).getHeader("Authorization");
// 判断是否有值
if (StringUtils.isNoneBlank(token)) {
// 设置当前session状态
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "url"); 
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);  
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);  
return token;
}
// 若header获取不到token则尝试从cookie中获取
return super.getSessionId(request, response);
}
}

你可能感兴趣的:(Shiro,前后端分离,Authorization,token,JavaWeb)