Shiro 認證失敗返回JSON


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");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM