从同一域的另一个网站登录laravel网站



网站A-简单的php表单网站B-Laravel网站

在网站A我有一个网站

这是网站A上从网站B 获取有效代币的功能

function getAuthToken() {
$.ajax({
url: 'https://B.website.test',
type: 'GET',
cache: false,
success: function (response) {
var csfr = $(response).filter('meta[name="csrf-token"]').prop('content');
var token = $(response).find('input[name="_token"]').val();
$('input[name="_token"]').val(token);
$('input[name="csrf-token"]').val(csfr);
},
error: function () {
//
}
});
}

这是应该进行登录的功能:

function doLogin() {
var _token = $('input[name="_token"]').val();
var email = $('input[name="email"]').val();
var password = $('input[name="password"]').val();
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
var cookieName = 'XSRF-TOKEN';
document.cookie = cookieName + "=" + _token + ";expires=" + myDate
+ ";domain=.website.test;path=/";
$.ajax({
headers: {
'XSRF-TOKEN': _token
},
url: 'http://B.website.test/doLogin',
type: 'POST',
data: {"_token": _token, "email": email, "password": password},
cache: false,
success: function (response) {
alert(response);
},
error: function () {
//
}
});

最后一条js:

$('#websiteb-login').on('click', function(e) {
e.preventDefault();
doLogin();
});

我在"网络"选项卡上得到的回复是419状态。有什么帮助吗?:D

您应该确保以下几点:

您需要确保您的AJAX请求使用以下选项发送cookie:

$.ajax({ 
url: 'http://B.website.test/doLogin',
type: 'POST',
data: {"_token": _token, "email": email, "password": password},
cache: false,
success: function (response) {
alert(response);
},
error: function () {
//
},
xhrFields: {  withCredentials: true }
}

或者,您可以将文档域设置为基本域,例如:

document.domain = 'website.test';

应该确保所有对网站子域的请求。测试不会触发CORS策略(也可能自动发送cookie(。

XSRF-TOKEN标头/cookie是加密的,因此您不能使用它们来发送令牌。只需将_token数据字段保持为当前状态即可。

最新更新