Shiro框架默認認證失敗后會返回到登錄頁面,在前后端分離項目中,需要返回JSON數據,以便前端或者app端解析處理。
實現方式:
1. 擴展shiro框架的UserFilter類,重寫redirectToLogin方法。
public class ShiroUserFilter extends UserFilter { @Override protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException { // super.redirectToLogin(request, response); response.setContentType("application/json; charset=utf-8");
//返回json response.getWriter().write(JSON.toJSONString(AjaxResult.error(401, "用戶未登錄,請先登錄"))); } }
2. 在Shiro 的ShiroFilterFactoryBean中加入filter,同時去掉登錄地址的配置
// 不需要設置登錄地址 //shiroFilterFactoryBean.setLoginUrl(loginUrl); filters.put("authc", new ShiroUserFilter()); filterChainDefinitionMap.put("/**", "authc,user,onlineSession,syncOnlineSession");