gpt4 book ai didi

jquery - 重定向后 HTML5 CORS 请求在 Safari 中失败

转载 作者:行者123 更新时间:2023-11-28 01:42:48 24 4
gpt4 key购买 nike

我正在使用 jQuery 设计一个 CORS 请求来完成一个 SSO 类型的系统。用户登录到 wordpress 并同时使用 Hook 登录到 Moodle。

我遇到的问题是,当初始 POST 请求设置为 moodlesite.com/login/index.php 时,在 Safari(并且只有 safari ~7+)中会重定向到:moodlesite.com/login/index.php?testsession=user_id.

发生此重定向时,Safari 会丢弃适用的 CORS header ,然后对重定向 URL 的请求将失败。

最佳答案

我发布这个问题只是为了回答它,因为我花了很长时间才找到解决这个 Safari 错误的方法。希望这对某人有所帮助。

我最后做的是创建另一个 ajax 请求,该请求在对 moodle 的实际请求之前运行。此请求使用 wordpress 的 AJAX 功能来生成到 moodle 服务器端的 CURL。这允许我获取重定向的 URL(其中包括用户的 moodle id)。然后在该请求完成后,我向 Moodle 服务器发出真正的请求。

示例代码:

// redirect follower ajax request to figure out what the final moodle login url is
// this is necessary becuase SAFARI 7.03 looses CORS headers on ajax requests
add_action( 'wp_ajax_lms_redirect_follower', 'lms_redirect_follower' );
add_action( 'wp_ajax_nopriv_lms_redirect_follower', 'lms_redirect_follower' );
function lms_redirect_follower(){
$url = 'http://'.get_field('moodle_url', 'options').'/login/index.php';
$username = $_POST['username'];
$password = $_POST['password'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=".$username."&password=".$password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$server_output = curl_exec ($ch);
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
echo $url;
die();
}

function moodle_sso ()
{ ?>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function crossDomainPost(user, pass) {
// first get the redirect url
var moodle_login_url = 'http://<?php the_field('moodle_url', 'options'); ?>/login/index.php';
var data = {
'action': 'lms_redirect_follower',
'username': user,
'password':pass
};
$.post("<?php echo admin_url( 'admin-ajax.php' ); ?>", data, function(response) {
moodle_login_url = response;
$.ajax({
type: 'POST',
url: moodle_login_url,
cache: false,
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: {"username":user, "password":pass},
success: function(responseData, textStatus, jqXHR) {
$('#loginform').submit();
},
error: function (responseData, textStatus, errorThrown) {
// console.log(errorThrown);
// console.log(responseData);
},
complete: function(responseData, textStatus, errorThrown){
// console.log(errorThrown);
// console.log(responseData);
}
});
});
}

$(document).ready(function(){
$('#wp-submit').click(function(ev){
ev.preventDefault();
return crossDomainPost($('#user_login').val(), $('#user_pass').val());
})
})

</script>
<?php
}
add_action('login_footer', 'moodle_sso');

关于jquery - 重定向后 HTML5 CORS 请求在 Safari 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24833312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com