title: How to make JWT cookie authentication in Laravel
body: <p>I want to have JWT authentication in Laravel >=5.2, using <a href="https://github.com/tymondesigns/jwt-auth" rel="noreferrer">this (Tymon JWT-auth) library</a> but I want to put JWT token into HttpOnly Cookies - to protect JWT token from steal from XSS attack. </p>
  
  <ol>
  <li>I set up Tymon library and... in project:  app/Providers/RouteServiceProvider@mapWebRoutes i deactivate execution 'web' middelware group for all requests (which is default laravel behavior - you can see it by <code>php artisan route:list</code>) by remove <code>'middleware' =&gt; 'web'</code> (If I don't do it, i will see CSRF problem with post request).</li>
  <li>in routes.php i write:</li>
  </ol>
  
  <blockquote>
  <pre><code>Route::group(['middleware' =&gt;'api', 'prefix' =&gt; '/api/v1', 'namespace' =&gt; 'Api\V1'], function () {
      Route::post('/login', 'Auth\AuthController@postLogin');
      ...
      Route::get('/projects', 'ProjectsController@getProjects');
  }
  </code></pre>
  </blockquote>
  
  <ol start="3">
  <li><p>In may Api\V1\Auth\AuthController@postLogin i generate token and send it back as httpOnly cookie:</p>
  
  <pre><code>...
  try
  {
      $user = User::where('email','=',$credentials['email'])-&gt;first();
  
      if ( !($user &amp;&amp; Hash::check($credentials['password'], $user-&gt;password) ))
      {
          return response()-&gt;json(['error' =&gt; 'invalid_credentials'], 401);
      }
  
      $customClaims = ['sub' =&gt; $user-&gt;id, 'role'=&gt; $user-&gt;role, 'csrf-token' =&gt; str_random(32) ];
      $payload = JWTFactory::make($customClaims);
      $token = JWTAuth::encode($payload);
  } catch(...) {...}
  return response()-&gt;json($payload-&gt;toArray())-&gt;withCookie('token', $token, config('jwt.ttl'), "/", null, false, true); 
  </code></pre></li>
  <li><p>And, yeah here question starts. I would like to do something (may be modifiy laravel <code>Auth</code> class) on each request:</p>
  
  <ul>
  <li>get coookie from request</li>
  <li>decode it</li>
  <li>check is right (if not trhow 401)</li>
  <li>get user from DB</li>
  <li>and make that method Auth::user() works every where like in usual way in laravel (so i can use it in each Controller for example)</li>
  </ul></li>
  </ol>
  
  <p>Any ideas how to do point 4 ?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I also add here protection for CSRF attack - csrf-token is in JWT, and it is also return in body of response for login request (so JS have acces to this csrf-token) (i return only public part of JWT token in login response, whole JWT is return only in cookie, so it is XSS safe) -  then front JS must copy csrf-token into header of each request. Then the middelware JWTAuthentiacate (in my answer below) compare csrf-token header with csrf-token field in JWT payload - if they are similar then request pass csrf test.</p>