Skip to content

Commit

Permalink
Allow passing multiple audiences in a single call
Browse files Browse the repository at this point in the history
Mainly to make it easier for end-users to add many permitted clients to
the token.

More info:
  - #291
  • Loading branch information
lcobucci committed Apr 16, 2019
1 parent 66d8669 commit b90925e
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 12 deletions.
4 changes: 2 additions & 2 deletions src/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
interface Builder
{
/**
* Appends a new audience
* Appends new items to audience
*/
public function permittedFor(string $audience): Builder;
public function permittedFor(string ...$audiences): Builder;

/**
* Configures the expiration time
Expand Down
13 changes: 6 additions & 7 deletions src/Token/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
use Lcobucci\JWT\Builder as BuilderInterface;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key;
use function array_diff;
use function array_intersect;
use function array_keys;
use function array_merge;
use function in_array;

final class Builder implements BuilderInterface
Expand Down Expand Up @@ -38,15 +40,12 @@ public function __construct(Parsing\Encoder $encoder)
/**
* {@inheritdoc}
*/
public function permittedFor(string $audience): BuilderInterface
public function permittedFor(string ...$audiences): BuilderInterface
{
$audiences = $this->claims[RegisteredClaims::AUDIENCE] ?? [];
$configured = $this->claims[RegisteredClaims::AUDIENCE] ?? [];
$toAppend = array_diff($audiences, $configured);

if (! in_array($audience, $audiences, true)) {
$audiences[] = $audience;
}

return $this->setClaim(RegisteredClaims::AUDIENCE, $audiences);
return $this->setClaim(RegisteredClaims::AUDIENCE, array_merge($configured, $toAppend));
}

/**
Expand Down
5 changes: 2 additions & 3 deletions test/unit/Token/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public function claimsMustBeFormattedWhileEncoding(): void
public function audienceShouldBeFormattedAsArrayWhenMultipleValuesAreUsed(): void
{
$headers = ['typ' => 'JWT', 'alg' => 'RS256'];
$claims = [RegisteredClaims::AUDIENCE => ['test1', 'test2']];
$claims = [RegisteredClaims::AUDIENCE => ['test1', 'test2', 'test3']];

$this->signer->method('sign')->willReturn('testing');

Expand All @@ -154,8 +154,7 @@ public function audienceShouldBeFormattedAsArrayWhenMultipleValuesAreUsed(): voi

$builder = new Builder($this->encoder);

$builder->permittedFor('test1')
->permittedFor('test2')
$builder->permittedFor('test1', 'test2', 'test3')
->permittedFor('test2') // should not be added since it's duplicated
->getToken($this->signer, new Key('123'));
}
Expand Down

0 comments on commit b90925e

Please sign in to comment.