Laravel 5.1. Token from and session token are diff

2019-08-09 23:42发布

问题:

I have got this login form:

<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    ...

I login with no problem using a browser from a desktop (IE, Chrome, Firefox, ...), but the problem comes from mobile device (android platform).

I got this exceptión:

TokenMismatchException in VerifyCsrfToken.php line 53.

When I went to VerifyCsrfToken.php I discovered that the token passed from the form and the token taked from session object are different. But this only happens from my android phone.

On function called tokensMatch in the file VerifyCsrfToken.php (link to github) I add this code to see what was happening:

echo '<br>X-CSRF-TOKEN:'.$request->header('X-CSRF-TOKEN');
echo '<br>X-XSRF-TOKEN:'.$request->header('X-XSRF-TOKEN');
echo '<br>token:'.$request->input('_token');
echo '<br>sessionToken:'.$request->session()->token();  

Token and sessionToken are different (the other two value are empty).

Any clues about this? This only happens using a mobile device (two android tested).

UPDATE: I set the token input to text to view the content from the browser. The thing is that in mobile devices when I refresh the url [domain.com]/auth/login, the token changes in every call, however, from desktop browser the token do not change. I think that in mobile devices the sessions is created and destroyed in every call.

UPDATE 2: I confirm that the problems comes by the changing of token in every request. I don't know that this happens only from mobile devices.

回答1:

Solved.

The problem was a wrong value of 'domain' key in session.php. On mobile devices for any reason the cookies policies are more restricted.

I had got this value:

'domain' => env('SESSION_DOMAIN', 'www.[mydomain].com'),

I need to remove www., so this value must be like this:

'domain' => env('SESSION_DOMAIN', '[mydomain].com'),

For any reason from desktop browser with no special configuration the cookie works with no problem.