首页 > 解决方案 > 为ajax URL启用spring安全性时重定向到Ajax Post Request上的登录页面

问题描述

我已经在我的 WebApp 中实现了 Spring-Security,当我点击 LIKE 按钮时,它会向服务器发送一个 ajax 请求

(我的网址是:http:localhost:8080/myWebApp/likes/qs/10)

我的这个 URL 的 spring 安全配置是

<http>  
<!-- Admin access Only -->
<intercept-url pattern="/manage/**" access="hasAuthority('ADMIN')" /> 
<!-- FOR USER -->
<intercept-url pattern="/likes/**" access="hasAuthority('USER')" method="POST"/> 
</http>

当浏览器中的 URL 更改时(第一种情况),它将用户重定向到登录页面。(工作正常)但在 ajax 请求的情况下,URL 被限制在服务器上发布,尽管如果用户未登录,它不会重定向到登录页面。

General
Request URL: http:localhost:8080/myWebApp/likes/qs/10
Request Method: POST
Status Code: 302 
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade

Resonse Header
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Thu, 20 Jun 2019 07:09:37 GMT
Expires: 0
Location: http://localhost:8080/eveprep/login
Pragma: no-cache
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

Request Header
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Connection: keep-alive
Content-Length: 0
Cookie: JSESSIONID=54E50C4CE1E32BD2FFDA60B6AE2992B9
Host: localhost:8080
Origin: http://localhost:8080
Referer: http://localhost:8080/eveprep/show/subCategory/1/mcqs/1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36
X-CSRF-TOKEN: 08599de2-8fb5-41c6-83dc-a4d034933a42
X-Requested-With: XMLHttpRequest

js文件

$('body').on('click','.likebtn',function(event) {
    var btn = $(this);
    var likeBtnId = btn.prop('id');
    var likeUrl = window.contextRoot+ '/likes/qs/'+ likeBtnId;                  
        $.post(likeUrl,function(data) {
            Swal.fire({
            toast: true,
            position: 'top-end',
            type: 'success',
            title: 'Unliked',
            showConfirmButton: false,
            timer: 1500
            })
        });
});

标签: jqueryajaxspring-mvcspring-security

解决方案


问题是,您不能在 ajax requests 中重定向用户。一种可能的解决方案可能是这样的:

  1. 为您的登录表单设置一个 ID。例如<form id="#loginForm">
  2. 在您的 ajax 请求的成功回调中,解析结果,如果包含#loginFormword,则表示用户未通过身份验证,spring 在访问受保护的 url 后将其重定向到登录页面。然后您可以使用 javascript 将他重定向到您的登录页面window.location

注意:在每个 ajax 请求中解析 ajax 结果是非常困难的,并且还需要进行许多代码更改。相反,您可以为所有 ajax 请求设置一次成功事件处理程序,并使用ajaxSuccess(). 使用此方法,您无需修改​​ ajax 调用方法。


推荐阅读