Skip to content

Commit

Permalink
Documentation
Browse files Browse the repository at this point in the history
* Document how to add/remove token extractors
  • Loading branch information
chalasr committed Sep 16, 2016
1 parent 3706b74 commit 358ff29
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 13 deletions.
1 change: 0 additions & 1 deletion Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
<argument type="service" id="lexik_jwt_authentication.jwt_manager"/>
<argument type="service" id="event_dispatcher"/>
<argument type="service" id="lexik_jwt_authentication.extractor.chain_extractor"/>
<argument type="string" /> <!-- Custom user identity field -->
</service>
<!-- Default JWT Token Authenticator -->
<service id="lexik_jwt_authentication.jwt_token_authenticator" parent="lexik_jwt_authentication.security.guard.jwt_token_authenticator" />
Expand Down
73 changes: 73 additions & 0 deletions Resources/doc/6-extending-jwt-authenticator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
Extending JWTTokenAuthenticator
===============================

The `JWTTokenAuthenticator` class is responsible of authenticating JWT tokens. It is used through the `lexik_jwt_authentication.guard.jwt_token_authenticator` which can be customized in the most flexible but still structured way to do it: _creating your own authenticators by extending the service_, so you can manage various security contexts in the same application.

Creating your own Token Authenticator
-------------------------------------

The following code can be used for creating your own authenticators.

```yaml
# services.yml
services:
app.jwt_token_authenticator:
class: AppBundle\Security\Guard\JWTTokenAuthenticator
parent: lexik_jwt_authentication.guard.jwt_token_authenticator
```
```php
namespace AppBundle\Security\Guard;

use Lexik\Bundle\JWTAuthenticationBundle\Security\Guard\JWTTokenAuthenticator as BaseAuthenticator;

class JWTTokenAuthenticator extends BaseAuthenticator
{
// Your own logic
}
```

__Note:__ The code examples of this section require to have this step done, it may not be repeated.

Using different Token Extractors per Authenticator
--------------------------------------------------

Token extractors are set up in the main configuration of this bundle, usually found in your `app/config/config.yml`.
If your application contains multiple firewalls with different security contexts, you may want to configure the different token extractors which should be used on each firewall respectively. This can be done by having as much authenticators as firewalls (for creating authenticators, see [the first section of this topic](#creating-your-own-token-authenticator)).


```php
namespace AppBundle\Security\Guard;

use Lexik\Bundle\JWTAuthenticationBundle\Security\Guard\JWTTokenAuthenticator as BaseAuthenticator;
use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor;

class JWTTokenAuthenticator extends BaseAuthenticator
{
/**
* @return TokenExtractor\TokenExtractorInterface
*/
protected function getTokenExtractor()
{
// Return a custom extractor, no matter of what are configured
return new TokenExtractor\AuthorizationHeaderTokenExtractor('Token', 'Authorization');

// Or retrieve the chain token extractor for mapping/unmapping extractors for this authenticator
$chainExtractor = parent::getTokenExtractor();

// Clear the token extractor map from all configured extractors
$chainExtractor->clearMap();

// Or only remove a specific extractor
$chainTokenExtractor->removeExtractor(function (TokenExtractor\TokenExtractorInterface $extractor) {
return $extractor instanceof TokenExtractor\CookieTokenExtractor;
});

// Add a new query parameter extractor to the configured ones
$chainExtractor->addExtractor(new TokenExtractor\QueryParameterTokenExtractor('jwt'));

// Return the chain token extractor with the new map
return $chainTokenExtractor;
}
}
```
24 changes: 22 additions & 2 deletions Security/Guard/JWTTokenAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
use Symfony\Component\Security\Guard\GuardAuthenticatorInterface;

/**
* JWTTokenAuthenticator (Guard strict implementation).
* JWTTokenAuthenticator (Guard implementation).
*
* @see http://knpuniversity.com/screencast/symfony-rest4/jwt-guard-authenticator
*
Expand Down Expand Up @@ -87,7 +87,13 @@ public function __construct(
*/
public function getCredentials(Request $request)
{
if (false === ($jsonWebToken = $this->tokenExtractor->extract($request))) {
$tokenExtractor = $this->getTokenExtractor();

if (!$tokenExtractor instanceof TokenExtractorInterface) {
throw new \RuntimeException(sprintf('Method "%s::getTokenExtractor()" must return an instance of "%s".', __CLASS__, TokenExtractorInterface::class));
}

if (false === ($jsonWebToken = $tokenExtractor->extract($request))) {
return;
}

Expand Down Expand Up @@ -226,4 +232,18 @@ public function supportsRememberMe()
{
return false;
}

/**
* Gets the token extractor to be used for retrieving a JWT token in the
* current request.
*
* Override this method for adding/removing extractors to the chain one or
* returning a different {@link TokenExtractorInterface} implementation.
*
* @return TokenExtractorInterface
*/
protected function getTokenExtractor()
{
return $this->tokenExtractor;
}
}
16 changes: 15 additions & 1 deletion Tests/TokenExtractor/ChainTokenExtractorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,20 @@ public function testAddExtractor()
$this->assertContains($custom, $map);
}

public function testRemoveExtractor()
{
$extractor = new ChainTokenExtractor([]);
$custom = $this->getTokenExtractorMock(null);

$extractor->addExtractor($custom);
$result = $extractor->removeExtractor(function (TokenExtractorInterface $extractor) use ($custom) {
return $extractor instanceof \PHPUnit_Framework_MockObject_MockObject;
});

$this->assertTrue($result, 'removeExtractor returns true in case of success, false otherwise');
$this->assertFalse($extractor->getIterator()->valid(), 'The token extractor should have been removed so the map should be empty');
}

public function testExtract()
{
$this->assertEquals('dummy', (new ChainTokenExtractor($this->getTokenExtractorMap([false, false, 'dummy'])))->extract(new Request()));
Expand All @@ -47,7 +61,7 @@ public function testClearMap()
$extractor = new ChainTokenExtractor($this->getTokenExtractorMap());
$extractor->clearMap();

$this->assertNull($extractor->getIterator()->current());
$this->assertFalse($extractor->getIterator()->valid());
}

private function getTokenExtractorMock($returnValue)
Expand Down
43 changes: 34 additions & 9 deletions TokenExtractor/ChainTokenExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
* ChainTokenExtractor is the class responsible of extracting a JWT token
* from a {@link Request} object using all mapped token extractors.
*
* Note: The extractor map is reinitialized to the configured extractors for
* each different instance.
*
* @author Robin Chalas <[email protected]>
*/
class ChainTokenExtractor implements \IteratorAggregate, TokenExtractorInterface
Expand Down Expand Up @@ -35,6 +38,36 @@ public function addExtractor(TokenExtractorInterface $extractor)
$this->map[] = $extractor;
}

/**
* Removes a token extractor from the map.
*
* @param Closure $filter A function taking an extractor as argument,
* used to find the extractor to remove,
*
* @return bool True in case of success, false otherwise
*/
public function removeExtractor(\Closure $filter)
{
$filtered = array_filter($this->map, $filter);

if (!$extractorToUnmap = current($filtered)) {
return false;
}

$key = array_search($extractorToUnmap, $this->map);
unset($this->map[$key]);

return true;
}

/**
* Clears the token extractor map.
*/
public function clearMap()
{
$this->map = [];
}

/**
* Iterates over the token extractors map calling {@see extract()}
* until a token is found.
Expand All @@ -58,7 +91,7 @@ public function extract(Request $request)
* An extractor is initialized only if we really need it (at
* the corresponding iteration).
*
* @return \Generator The generated TokenExtractorInterface implementations
* @return \Generator The generated {@link TokenExtractorInterface} implementations
*/
public function getIterator()
{
Expand All @@ -68,12 +101,4 @@ public function getIterator()
}
}
}

/**
* Clears the token extractor map.
*/
public function clearMap()
{
$this->map = [];
}
}

0 comments on commit 358ff29

Please sign in to comment.