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:80
からへの AJAX リクエストを作成していますhttp://localhost:8080
。
Chrome で
アクセスしようとすると、OPTIONS プリフライト リクエストのj_spring_security_check
ため(pending)
に Chrome にアクセスし、AJAX 呼び出しで HTTP ステータス コード 0 とメッセージ「エラー」が返されます。
Firefox の場合
プリフライトは 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 に POST できます。私は多くの記事を読んできたので、この奇妙な問題についての洞察をいただければ幸いです