Created
April 4, 2018 14:46
-
-
Save gpressutto5/089a003fe86dd9c363d843101b7fd764 to your computer and use it in GitHub Desktop.
Bearer JWT Login for Laravel HTTP Testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests\Feature; | |
use App\User; | |
use Tymon\JWTAuth\Facades\JWTAuth; | |
/** | |
* Trait WithAuth | |
* | |
* @package Tests\Feature | |
* @author Guilherme Pressutto <[email protected]> | |
*/ | |
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