springboot+shiro前后端分离返回json

首先处理由于前后端分离导致的session不通问题
要在前段登录之后存储登录成功的token,之后每次请求在head中传递此token,然后后台添加如下类

/**
 * 创建人: chenyidong
 * 创建时间: 2020/1/3 下午12:22
 * 说明: fangchan:自定义session生成方式
 */
public class MySessionManager extends DefaultWebSessionManager {
     

    private Logger logger = Logger.getLogger("MySessionManager");



    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response){
     
        String id = WebUtils.toHttp(request).getHeader("token");
        if(StringUtils.isEmpty(id)){
     
            //如果没有携带id参数则按照父类的方式在cookie进行获取
            return super.getSessionId(request, response);
        }else{
     
            //如果请求头中有 authToken 则其值为sessionId
            logger.info("使用传递session"+id);
            request.setAttribute(REFERENCED_SESSION_ID_SOURCE,"Stateless request");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);
            return id;
        }
    }


}

下面过滤传递过来的token是否有效

public class FormValidataFilter extends FormAuthenticationFilter {
     

    private Logger logger = Logger.getLogger("FormValidataFilter");


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
     
        if (isLoginRequest(request, response)) {
     
            if (isLoginSubmission(request, response)) {
     
                return executeLogin(request, response);
            } else {
     
                return true;
            }
        } else {
     
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "4001");
            jsonObject.put("message", "登录失效,请重新登录");
            writer.print(jsonObject);
            return false;
        }
    }

}

你可能感兴趣的:(Shiro)