Shiro拦截器,在登录时判断是ajax请求返回json,普通请求跳转页面

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/pengbin790000/article/details/84531914

在使用shiro时,会遇到普通的页面请求以及api接口调用的请求,因此需要区别对待来判断是跳转登录页面还是返回json的数据:

1.创建拦截器

package org.zyyd.base.filter;

import com.alibaba.fastjson.JSONObject;

import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component("ApiCustomUser")
public class ApiCustomUserFilter extends UserFilter {

    /**
     * 拦截时返回  JSON,而不是跳转到一个loginUrl
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request,
                                     ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if(isAjaxRequest(req)){
            JSONObject json = new JSONObject();
            json.put("code", "-999");
            json.put("message", "尚未登录!");

            writeJson(json,res);
        }else{
            redirectToLogin(request, response);
        }

        return false;
    }


    /**
     *   是否是Ajax请求
     * @Description:
     * @param
     * @return
     * @throws
     * @author pengbin <pengbin>
     * 2018/11/26 10:58
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }


    /**
     *   输出JSON
     * @Description:
     * @param
     * @return
     * @throws
     * @author pengbin <pengbin>
     * 2018/11/26 10:59
     */
    private void writeJson(JSONObject json, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            out.write(json.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

继承shiro的UserFilter并且重写onAccessDenied

2.修改配置:

<!-- 对应于web.xml中配置的那个shiroFilter -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- Shiro的核心安全接口,这个属性是必须的 -->
		<property name="securityManager" ref="securityManager"/>
		<!-- 要求登录时的链接(登录页面地址),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
		<property name="loginUrl" value="/login.html"/>
		<!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码) -->
		<!-- <property name="successUrl" value="/" ></property> -->
		<!-- 用户访问未对其授权的资源时,所显示的连接 -->
		<!--<property name="unauthorizedUrl" value="/error/unauthorized"/>-->

        <!-- Shiro连接约束配置,即过滤链的定义 -->
        <!-- 此处可配合这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839 -->
        <!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->
        <!-- anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->
        <!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
        <property name="filterChainDefinitions">
            <value>


                <!--/** =authc-->
				/** = ApiCustomUser

            </value>
        </property>

参考资料:https://blog.csdn.net/qq737050283/article/details/60876473

猜你喜欢

转载自blog.csdn.net/pengbin790000/article/details/84531914