tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.24k stars 1.55k forks source link

how to get jwt for testing #2169

Open richoandika opened 2 years ago

richoandika commented 2 years ago

i'm so tired, there is no documentation on how to use jwt for testing in lumen. can anybody helpme?

pildit commented 2 years ago

What kind of testing ? with PhpUnit ?

If yes, you can use actingAs for sending requests :

        $response = $this->actingAs($this->companyUser->user, 'api')
                    ->json(
                        'POST',
                        '/company/talent/technical-test',
                        $payload
                    );

I use 'api' because i'm testing an API implementation

orlov-vo commented 2 years ago

The actingAs method doesn't help me :((

Tymon\JWTAuth\Exceptions\JWTException(code: 0): Token could not be parsed from the request. at /var/www/html/vendor/tymon/jwt-auth/src/JWTGuard.php:402

orlov-vo commented 2 years ago

Solved it by overriding actingAs method in abstract TestCase class:

    /**
     * @inheritDoc
     */
    public function actingAs(UserContract $user, $guard = null)
    {
        parent::actingAs($user, $guard);

        $token = auth()->login($user);
        $this->withHeaders(array_merge([$this->defaultHeaders, ['Authorization' => 'Bearer ' . $token]]));

        return $this;
    }