Skip to content

Commit b1bfb35

Browse files
authored
Update testing JWT Authentication with ApiTestCase (#1242)
* Update testing with ApiTestCase * fix typos
1 parent 5aaf518 commit b1bfb35

File tree

1 file changed

+40
-49
lines changed

1 file changed

+40
-49
lines changed

core/jwt.md

Lines changed: 40 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -298,69 +298,60 @@ services:
298298
autoconfigure: false
299299
```
300300
301-
## Testing with Behat
301+
## Testing
302302
303-
Let's configure Behat to automatically send an `Authorization` HTTP header containing a valid JWT token when a scenario is marked with a `@login` annotation. Edit `features/bootstrap/FeatureContext.php` and add the following methods:
303+
To test your authentication with `ApiTestCase`, you can write a method as below:
304304

305305
```php
306306
<?php
307-
// features/bootstrap/FeatureContext.php
307+
// tests/AuthenticationTest.php
308308
309+
namespace App\Tests;
310+
311+
use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\ApiTestCase;
309312
use App\Entity\User;
310-
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
311-
use Behatch\Context\RestContext;
313+
use Hautelook\AliceBundle\PhpUnit\ReloadDatabaseTrait;
312314
313-
class FeatureContext implements Context, SnippetAcceptingContext
315+
class AuthenticationTest extends ApiTestCase
314316
{
315-
// ...
316-
// Must be after createDatabase() and dropDatabase() functions (the order matters)
317-
318-
/**
319-
* @BeforeScenario
320-
* @login
321-
*
322-
* @see https://symfony.com/doc/current/security/entity_provider.html#creating-your-first-user
323-
*/
324-
public function login(BeforeScenarioScope $scope)
317+
use ReloadDatabaseTrait;
318+
319+
public function testLogin(): void
325320
{
326-
$user = new User();
327-
$user->setUsername('admin');
328-
$user->setPassword('ATestPassword');
329-
$user->setEmail('[email protected]');
321+
$client = self::createClient();
330322
331-
$this->manager->persist($user);
332-
$this->manager->flush();
323+
$user = new User();
324+
$user->setEmail('[email protected]');
325+
$user->setPassword(
326+
self::$container->get('security.password_encoder')->encodePassword($user, '$3CR3T')
327+
);
328+
329+
$manager = self::$container->get('doctrine')->getManager();
330+
$manager->persist($user);
331+
$manager->flush();
332+
333+
// retrieve a token
334+
$response = $client->request('POST', '/authentication_token', [
335+
'headers' => ['Content-Type' => 'application/json'],
336+
'json' => [
337+
'email' => '[email protected]',
338+
'password' => '$3CR3T',
339+
],
340+
]);
333341
334-
$token = $this->jwtManager->create($user);
342+
$json = $response->toArray();
343+
$this->assertResponseIsSuccessful();
344+
$this->assertArrayHasKey('token', $json);
335345
336-
$this->restContext = $scope->getEnvironment()->getContext(RestContext::class);
337-
$this->restContext->iAddHeaderEqualTo('Authorization', "Bearer $token");
338-
}
346+
// test not authorized
347+
$client->request('GET', '/greetings');
348+
$this->assertResponseStatusCodeSame(401);
339349
340-
/**
341-
* @AfterScenario
342-
* @logout
343-
*/
344-
public function logout() {
345-
$this->restContext->iAddHeaderEqualTo('Authorization', '');
350+
// test authorized
351+
$client->request('GET', '/greetings', ['auth_bearer' => $json['token']]);
352+
$this->assertResponseIsSuccessful();
346353
}
347354
}
348355
```
349356

350-
Then, update `behat.yml` to inject the `lexik_jwt_authentication.jwt_manager`:
351-
352-
```yaml
353-
# behat.yml
354-
default:
355-
# ...
356-
suites:
357-
default:
358-
contexts:
359-
- FeatureContext: { doctrine: '@doctrine', 'jwtManager': '@lexik_jwt_authentication.jwt_manager' }
360-
- Behat\MinkExtension\Context\MinkContext
361-
- Behatch\Context\RestContext
362-
- Behatch\Context\JsonContext
363-
# ...
364-
```
365-
366-
Finally, mark your scenarios with the `@login` annotation to automatically add a valid `Authorization` header, and with `@logout` to be sure to destroy the token after this scenario.
357+
Refer to [Testing the API](../distribution/testing.md) for more information about testing API Platform.

0 commit comments

Comments
 (0)