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

猜你喜欢

转载自www.cnblogs.com/csts/p/11038454.html