Skip to content

Instantly share code, notes, and snippets.

@gpressutto5
Created April 4, 2018 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpressutto5/089a003fe86dd9c363d843101b7fd764 to your computer and use it in GitHub Desktop.
Save gpressutto5/089a003fe86dd9c363d843101b7fd764 to your computer and use it in GitHub Desktop.
Bearer JWT Login for Laravel HTTP Testing
<?php
namespace Tests\Feature;
use App\User;
use Tymon\JWTAuth\Facades\JWTAuth;
/**
* Trait WithAuth
*
* @package Tests\Feature
* @author Guilherme Pressutto <gpressutto5@gmail.com>
*/
trait WithAuth
{
/**
* The logged in user.
*
* @var User
*/
protected $user;
/**
* The JWT token for the logged in user.
*
* @var string
*/
protected $token;
/**
* Logs in with the given user or with a new one.
*
* @param User|null $user
*
* @return void
*/
protected function logIn(User $user = null)
{
$this->user = $user ?: factory(User::class)->create();
$this->token = JWTAuth::fromUser($this->user);
$this->withHeaders([
'Authorization' => "Bearer {$this->token}",
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment