2

csrf_token and X-XSRF-TOKEN have been added via Angular

$http.defaults.headers.common['csrf_token'] = CSRF_TOKEN;
$http.defaults.headers.common['X-XSRF-TOKEN'] = X_XSRF_TOKEN;

The project is working fine on local server but not in production. I see TokenMismatchException after submitting a form and Auth::attempt() works fine during login. But after login when I access user's id by Auth::user()->id for other route then I see no login user.

I also checked my cookies in local server. I can see XSRF-TOKEN and laravel-session there but in production my cookie list is empty.

Update: Found out that session is not working in my project on server.

Imran Hossain
  • 606
  • 5
  • 16

1 Answers1

4

Solution

The problem why the Session was not working is that a blank line was present before PHP opening tag(<?php) in a Config file(in my case /config/google-geocoder.php) of my project. That's why Laravel was unable to create any sessions(with laravel's default XSRF-token and laravel-session also) in the cookie list. See @codesidekick's answer from the link which helped me a lot to fix this issue. CSRF - Form Token Doesn't Match Session Token

Why localhost not facing this issue?

I can't tell exactly why but my Local Server has PHP version 5.5.9-1ubuntu4.19 and Production Server has 5.5.30. I think due to some difference in configuration, I faced the problem in production.

List of issues that can generate this problem

During my investigation I found out that there are several issues that may generate this problem. I have also included my one in the list below.

  • If you see any blank line before <!DOCTYPE html> of your source code from browser then the related files of your page has blank line before opening PHP tag. In this case check for realted PHP files created by you for the page and if there is none then look into default loaded files (index.php, routes.php, config files etc) of Laravel and make sure there is no blank space before PHP opening tag you added mistakenly.
  • If there is any echo right after data store in session.
  • If you have any whitespace after your closing tags. See here
  • If you are only having token mismatch then add token globally <meta name="_token" content="{!! csrf_token() !!}"/> into your header or locally in your form <input type="hidden" name="_token" value="{ csrf_token() }">. For ajax call

     $.ajaxSetup(
    {
        headers:
        {
            'X-CSRF-Token': $('input[name="_token"]').val()
        }
    });
    
  • Check whether /store/framework/Session has permission to store session because by default Laravel has File typed session. You may try Database session and I saw for some people it worked. You may try also to delete file cache from storage/framework/sessions and storage/framework/viewsSee @gbrock's answer

  • Some people said to clear cache and restart the server.

Community
  • 1
  • 1
Imran Hossain
  • 606
  • 5
  • 16