重定向浏览器中的 AngularJS 页面从 Java(Spring)过滤器

huangapple go评论82阅读模式
英文:

Redirect angular js page in browser from Java (Spring) Filter

问题

我在我的Spring Boot应用程序中创建了一个SQL注入过滤器它会拦截每个请求并验证可能受到SQL注入的输入如果输入无效我想将用户重定向回登录页面使用我的代码我可以看到通过DevTools进行了内部调用但浏览器未重定向到指定页面

过滤器

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String url = req.getRequestURL().toString();
    
    Enumeration<String> enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {
        String paramName = enumeration.nextElement();
        String value = request.getParameter(paramName);
        String sqlRegex =
            "\\b(ALTER\\s+TABLE{0,1}|CREATE\\s+TABLE{0,1}|DELETE\\s+FROM{0,1}|DROP\\s+TABLE{0,1}|EXEC(UTE){0,1}|INSERT\\s+INTO{0,1}|MERGE\\s+INTO{0,1}|SELECT\\s[0-9a-zA-Z_*]*\\s+FROM{0,1}|UPDATE\\s[0-9a-zA-Z_]*\\s+SET{0,1}|UNION\\n+ALL{0,1})\\b";
        int bufferOverflowLength = 4000;
        if (value != null && (Pattern.compile(sqlRegex).matcher(value.toUpperCase()).find()) || value.length() >= bufferOverflowLength) {
            HttpServletResponse resp = (HttpServletResponse) response;
            String redirectUrl = req.getContextPath() + "/logout";
            resp.setStatus(403);
            resp.sendRedirect(redirectUrl);
            return;
        }
    }
}
如何强制浏览器重定向到登出页面

更新
根据@buettner123的评论我在Angular中实现了一个httpInterceptor但仍无法拦截我的来自过滤器的请求

Angular拦截器代码

$httpProvider.interceptors.push(['$location', '$injector', '$q', function ($location, $injector, $q) {
    return {
        'request': function (config) {
            console.log("Request intercepted");
            return config;
        },
        'responseError': function (rejection) {
            console.log("Response Error Intercepted");
            return $q.reject(rejection);
        },
        'response': function(response) {
            // 在成功时执行一些操作
            console.log('我完成了');
            var status = response.status;
            console.log(status);
            return response;
        }
    };
}]);
英文:

I have created an SQL injection filter in my Spring Boot application that intercepts each request and validates input for a possible SQL injection. If input is invalid, then I want to redirect user back to login page. With my code, I can see internal call being made through DevTools but browser is not redirecting to specified page.

Filter

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

HttpServletRequest req = (HttpServletRequest) request;
String url = req.getRequestURL().toString();

Enumeration&lt;String&gt; enumeration = request.getParameterNames();
while (enumeration.hasMoreElements()) {
	String paramName = enumeration.nextElement();
	String value = request.getParameter(paramName);
	String sqlRegex =
					&quot;\\b(ALTER\\s+TABLE{0,1}|CREATE\\s+TABLE{0,1}|DELETE\\s+FROM{0,1}|DROP\\s+TABLE{0,1}|EXEC(UTE){0,1}|INSERT\\s+INTO{0,1}|MERGE\\s+INTO{0,1}|SELECT\\s[0-9a-zA-Z_*]*\\s+FROM{0,1}|UPDATE\\s[0-9a-zA-Z_]*\\s+SET{0,1}|UNION\\n+ALL{0,1})\\b&quot;;
	int bufferOverflowLength = 4000;
	if (value != null &amp;&amp; (Pattern.compile(sqlRegex).matcher(value.toUpperCase()).find()) || value.length() &gt;= bufferOverflowLength) {
		HttpServletResponse resp = (HttpServletResponse) response;
		String redirectUrl = req.getContextPath() + &quot;/logout&quot;;
        resp.setStatus(403);
		resp.sendRedirect(redirectUrl);
		return;
	}
}

}

How can I force browser to redirect to logout page?

Update:
As per @buettner123's comment, I have implemented an httpInterceptor in Angular, but that is still unable to intercept my request from Filter.

Angular Interceptor code

$httpProvider.interceptors.push([&#39;$location&#39;, &#39;$injector&#39;, &#39;$q&#39;, function ($location, $injector, $q) {
	return {
		&#39;request&#39;: function (config) {
			console.log(&quot;Request intercepted&quot;);
			return config;
		},
		&#39;responseError&#39;: function (rejection) {
			console.log(&quot;Response Error Intercepted&quot;);
			return $q.reject(rejection);
		},
		&#39;response&#39;: function(response) {
	        // do something on success
	        console.log(&#39;I am done&#39;);
            var status = response.status;
            console.log(status);
	        return response;
	      }
	};
}]);

答案1

得分: 0

以下是您提供的内容的翻译:

在此处发布解决方案,以防其他人可能遇到相同的问题

Filter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    String url = req.getRequestURL().toString();
    System.out.println("url : " + url);

    Enumeration<String> enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {

        String paramName = enumeration.nextElement();
        String value = request.getParameter(paramName);
        String sqlRegex =
                        "\\b(ALTER\\s+TABLE{0,1}|CREATE\\s+TABLE{0,1}|DELETE\\s+FROM{0,1}|DROP\\s+TABLE{0,1}|EXEC(UTE){0,1}|INSERT\\s+INTO{0,1}|MERGE\\s+INTO{0,1}|SELECT\\s[0-9a-zA-Z_*]*\\s+FROM{0,1}|UPDATE\\s[0-9a-zA-Z_]*\\s+SET{0,1}|UNION\\n+ALL{0,1})\\b";

        if (value != null && (Pattern.compile(sqlRegex).matcher(value.toUpperCase()).find())) {
            HttpSession session = req.getSession(false);
            if (session != null)
                session.invalidate();
            HttpServletResponse resp = (HttpServletResponse) response;
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SQL注入检测到");
            return;
        }
    }
}

main.js

$httpProvider.interceptors.push(['$location', '$injector', '$q', function ($location, $injector, $q) {
    return {
        'request': function (config) {
            return config;
        },
        'responseError': function (rejection) {
            if (rejection.status == 403 && rejection.data.includes("SQL注入")) {
                console.log("禁止访问资源");
                window.location.href = "重定向URL";
            }

            return $q.reject(rejection);
        },
        'response': function(response) {
            return response;
          }
    };
}]);

确保将 JavaScript 代码放在配置元素下。

英文:

Posting the solution here in-case someone else might find themselves with the same problem

Filter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    String url = req.getRequestURL().toString();
    System.out.println(&quot;url : &quot; + url);

    Enumeration&lt;String&gt; enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {

        String paramName = enumeration.nextElement();
        String value = request.getParameter(paramName);
        String sqlRegex =
                        &quot;\\b(ALTER\\s+TABLE{0,1}|CREATE\\s+TABLE{0,1}|DELETE\\s+FROM{0,1}|DROP\\s+TABLE{0,1}|EXEC(UTE){0,1}|INSERT\\s+INTO{0,1}|MERGE\\s+INTO{0,1}|SELECT\\s[0-9a-zA-Z_*]*\\s+FROM{0,1}|UPDATE\\s[0-9a-zA-Z_]*\\s+SET{0,1}|UNION\\n+ALL{0,1})\\b&quot;;

        if (value != null &amp;&amp; (Pattern.compile(sqlRegex).matcher(value.toUpperCase()).find())) {
            HttpSession session = req.getSession(false);
            if (session != null)
                session.invalidate();
            HttpServletResponse resp = (HttpServletResponse) response;
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, &quot;SQL injection detected&quot;);
            return;
        }
    }

}

main.js

$httpProvider.interceptors.push([&#39;$location&#39;, &#39;$injector&#39;, &#39;$q&#39;, function ($location, $injector, $q) {
return {
	&#39;request&#39;: function (config) {
		return config;
	},
	&#39;responseError&#39;: function (rejection) {
		if (rejection.status == 403 &amp;&amp; rejection.data.includes(&quot;SQL injection&quot;)) {
			console.log(&quot;Forbidden Resource&quot;);
			window.location.href=&quot;redirect url&quot;;
		}

		return $q.reject(rejection);
	},
	&#39;response&#39;: function(response) {
		return response;
	  }
};}]);

Make sure js code is under config element

huangapple
  • 本文由 发表于 2020年8月25日 17:41:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63576101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定