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


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);
请注意 - 我可以通过CORS发布到应用程序中的任何其他URL,除了Spring Security登录。我已经看过很多文章,所以任何对这个奇怪问题的见解将不胜感激。
 
					 
				 
				    		 
				    		 
				    		 
				    		