我试图让 CORS 与 Spring Security 很好地配合,但它不符合要求。我进行了本文中描述的更改,并更改了这一行,applicationContext-security.xml使 POST 和 GET 请求适用于我的应用程序(暂时公开控制器方法,因此我可以测试 CORS):
- 前:<intercept-url pattern="/**" access="isAuthenticated()" />
- 后:<intercept-url pattern="/**" access="permitAll" />
不幸的是,以下允许通过 AJAX 登录 Spring Security 的 URL 没有响应:http://localhost:8080/mutopia-server/resources/j_spring_security_check. 我正在从http://localhost:80to发出 AJAX 请求http://localhost:8080。
在 Chrome 中
尝试访问时,j_spring_security_check我进入(pending)Chrome 以获取 OPTIONS 预检请求,并且 AJAX 调用返回 HTTP 状态代码 0 和消息“错误”。
在火狐中
预检以 HTTP 状态代码 302 成功,之后我仍然会直接收到我的 AJAX 请求的错误回调,其中包含 HTTP 状态 0 和消息“错误”。


AJAX 请求代码
function get(url, json) {
    var args = {
        type: 'GET',
        url: url,
        // async: false,
        // crossDomain: true,
        xhrFields: {
            withCredentials: false
        },
        success: function(response) {
            console.debug(url, response);
        },
        error: function(xhr) {
            console.error(url, xhr.status, xhr.statusText);
        }
    };
    if (json) {
        args.contentType = 'application/json'
    }
    $.ajax(args);
}
function post(url, json, data, dataEncode) {
    var args = {
        type: 'POST',
        url: url,
        // async: false,
        crossDomain: true,
        xhrFields: {
            withCredentials: false
        },
        beforeSend: function(xhr){
            // This is always added by default
            // Ignoring this prevents preflight - but expects browser to follow 302 location change
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader("X-Ajax-call", "true");
        },
        success: function(data, textStatus, xhr) {
            // var location = xhr.getResponseHeader('Location');
            console.error('success', url, xhr.getAllResponseHeaders());
        },
        error: function(xhr) {
            console.error(url, xhr.status, xhr.statusText);
            console.error('fail', url, xhr.getAllResponseHeaders());
        }
    }
    if (json) {
        args.contentType = 'application/json'
    }
    if (typeof data != 'undefined') {
        // Send JSON raw in the body
        args.data = dataEncode ? JSON.stringify(data) : data;
    }
    console.debug('args', args);
    $.ajax(args);
}
var loginJSON = {"j_username": "username", "j_password": "password"};
// Fails
post('http://localhost:8080/mutopia-server/resources/j_spring_security_check', false, loginJSON, false);
// Works
post('http://localhost/mutopia-server/resources/j_spring_security_check', false, loginJSON, false);
// Works
get('http://localhost:8080/mutopia-server/landuses?projectId=6', true);
// Works
post('http://localhost:8080/mutopia-server/params', true, {
    "name": "testing",
    "local": false,
    "generated": false,
    "project": 6
}, true);
请注意 - 除了 Spring Security 登录之外,我可以通过 CORS 发布到我的应用程序中的任何其他 URL。我已经阅读了很多文章,因此对这个奇怪问题的任何见解将不胜感激