Skip to content

Commit

Permalink
Merge pull request #65 from bizley/v4.1.1
Browse files Browse the repository at this point in the history
4.1.1
  • Loading branch information
bizley authored Aug 17, 2024
2 parents e96172e + 083a3a3 commit 42cdaf3
Show file tree
Hide file tree
Showing 17 changed files with 453 additions and 434 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
run: composer i --prefer-dist --no-interaction --no-progress --optimize-autoloader

- name: PHPStan tests
run: vendor/bin/phpstan analyze -l 9 -a vendor/yiisoft/yii2/Yii.php --no-progress src
run: sh phpstan.sh

Infection:
name: PHP ${{ matrix.php }}
Expand Down
2 changes: 1 addition & 1 deletion CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ further defined and clarified by project maintainers.
## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at pawel@positive.codes. All
reported by contacting the project team at pawel[email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ Configuration array can be as the following:
]
```

- key (`bizley\jwt\Jwt::KEY`) - _string_, default `''`,
- key (`bizley\jwt\Jwt::KEY`) - _string_, default `''`, start it with `@` if it's Yii alias,
- passphrase (`bizley\jwt\Jwt::PASSPHRASE`) - _string_, default `''`,
- method (`bizley\jwt\Jwt::METHOD`) - _string_, default `bizley\jwt\Jwt::METHOD_PLAIN`,
available: `bizley\jwt\Jwt::METHOD_PLAIN`, `bizley\jwt\Jwt::METHOD_BASE64`, `bizley\jwt\Jwt::METHOD_FILE`
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"infection/infection": "*",
"lcobucci/clock": "^3.0",
"phpstan/phpstan": "*",
"phpunit/phpunit": "^10.0",
"phpunit/phpunit": "^10.5",
"roave/security-advisories": "dev-latest"
},
"autoload": {
Expand Down
4 changes: 2 additions & 2 deletions infection.json.dist
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
"@default": true,
"MethodCallRemoval": {
"ignore": [
"bizley\\jwt\\Jwt::init::124",
"bizley\\jwt\\JwtHttpBearerAuth::init::72"
"bizley\\jwt\\Jwt::init::117",
"bizley\\jwt\\JwtHttpBearerAuth::init::68"
]
}
},
Expand Down
49 changes: 21 additions & 28 deletions src/Jwt.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,7 @@

namespace bizley\jwt;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\ClaimsFormatter;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\Validation;
use Lcobucci\JWT\Validator;
use Lcobucci\JWT as BaseJwt;
use yii\base\InvalidConfigException;

/**
Expand All @@ -21,7 +14,7 @@
* This implementation is based on the \Lcobucci\JWT\Configuration setup which requires both signing and verifying keys
* to be defined (the standard way). If you need only some JWT tools, please use \bizley\jwt\JwtTools directly.
*
* @author Paweł Bizley Brzozowski <pawel@positive.codes> since 2.0 (fork)
* @author Paweł Bizley Brzozowski <pawel[email protected]> since 2.0 (fork)
* @author Dmitriy Demin <[email protected]> original package
*/
class Jwt extends JwtTools
Expand Down Expand Up @@ -50,7 +43,7 @@ class Jwt extends JwtTools
public const PASSPHRASE = 'passphrase';

/**
* @var string|array<string, string>|Signer\Key Signing key definition.
* @var string|array<string, string>|BaseJwt\Signer\Key Signing key definition.
* This can be a simple string, an instance of Key, or a configuration array.
* The configuration takes the following array keys:
* - 'key' => Key's value or path to the key file.
Expand All @@ -77,7 +70,7 @@ class Jwt extends JwtTools
public $signingKey = '';

/**
* @var string|array<string, string>|Signer\Key Verifying key definition.
* @var string|array<string, string>|BaseJwt\Signer\Key Verifying key definition.
* $signingKey documentation you can find above applies here as well.
* Symmetric algorithms (like HMAC) use a single key to sign and verify tokens so this property is ignored in that
* case. Asymmetric algorithms (like RSA and ECDSA) use a private key to sign and a public key to verify.
Expand All @@ -86,7 +79,7 @@ class Jwt extends JwtTools
public $verifyingKey = '';

/**
* @var string|Signer Signer ID or Signer instance to be used for signing/verifying.
* @var string|BaseJwt\Signer Signer ID or Signer instance to be used for signing/verifying.
* See $signers for available values. Since 4.0.0 it cannot be empty anymore.
* @since 3.0.0
*/
Expand Down Expand Up @@ -114,7 +107,7 @@ class Jwt extends JwtTools
],
];

private ?Configuration $configuration = null;
private ?BaseJwt\Configuration $configuration = null;

/**
* @throws InvalidConfigException
Expand All @@ -124,18 +117,18 @@ public function init(): void
parent::init();

$signerId = $this->signer;
if ($this->signer instanceof Signer) {
if ($this->signer instanceof BaseJwt\Signer) {
$signerId = $this->signer->algorithmId();
}
if (\in_array($signerId, $this->algorithmTypes[self::SYMMETRIC], true)) {
$this->configuration = Configuration::forSymmetricSigner(
$this->configuration = BaseJwt\Configuration::forSymmetricSigner(
$this->buildSigner($this->signer),
$this->buildKey($this->signingKey),
$this->prepareEncoder(),
$this->prepareDecoder()
);
} elseif (\in_array($signerId, $this->algorithmTypes[self::ASYMMETRIC], true)) {
$this->configuration = Configuration::forAsymmetricSigner(
$this->configuration = BaseJwt\Configuration::forAsymmetricSigner(
$this->buildSigner($this->signer),
$this->buildKey($this->signingKey),
$this->buildKey($this->verifyingKey),
Expand All @@ -151,7 +144,7 @@ public function init(): void
* @throws InvalidConfigException
* @since 3.0.0
*/
public function getConfiguration(): Configuration
public function getConfiguration(): BaseJwt\Configuration
{
if ($this->configuration === null) {
throw new InvalidConfigException('Configuration has not been set up. Did you call init()?');
Expand All @@ -165,7 +158,7 @@ public function getConfiguration(): Configuration
* @see https://lcobucci-jwt.readthedocs.io/en/latest/issuing-tokens/ for details of using the builder.
* @throws InvalidConfigException
*/
public function getBuilder(?ClaimsFormatter $claimFormatter = null): Builder
public function getBuilder(?BaseJwt\ClaimsFormatter $claimFormatter = null): BaseJwt\Builder
{
return $this->getConfiguration()->builder($claimFormatter);
}
Expand All @@ -174,7 +167,7 @@ public function getBuilder(?ClaimsFormatter $claimFormatter = null): Builder
* @see https://lcobucci-jwt.readthedocs.io/en/latest/parsing-tokens/ for details of using the parser.
* @throws InvalidConfigException
*/
public function getParser(): Parser
public function getParser(): BaseJwt\Parser
{
return $this->getConfiguration()->parser();
}
Expand All @@ -183,51 +176,51 @@ public function getParser(): Parser
* @see https://lcobucci-jwt.readthedocs.io/en/stable/validating-tokens/ for details of using the validator.
* @throws InvalidConfigException
*/
public function getValidator(): Validator
public function getValidator(): BaseJwt\Validator
{
return $this->getConfiguration()->validator();
}

/**
* This method goes through every single constraint in the set, groups all the violations, and throws an exception
* with the grouped violations.
* @param non-empty-string|Token $jwt JWT string or instance of Token
* @throws Validation\RequiredConstraintsViolated When constraint is violated
* @throws Validation\NoConstraintsGiven When no constraints are provided
* @param non-empty-string|BaseJwt\Token $jwt JWT string or instance of Token
* @throws BaseJwt\Validation\RequiredConstraintsViolated When constraint is violated
* @throws BaseJwt\Validation\NoConstraintsGiven When no constraints are provided
* @throws InvalidConfigException
* @since 3.0.0
*/
public function assert($jwt): void
{
$configuration = $this->getConfiguration();
$token = $jwt instanceof Token ? $jwt : $this->parse($jwt);
$token = $jwt instanceof BaseJwt\Token ? $jwt : $this->parse($jwt);
$constraints = $this->prepareValidationConstraints();
$configuration->validator()->assert($token, ...$constraints);
}

/**
* This method return false on first constraint violation
* @param non-empty-string|Token $jwt JWT string or instance of Token
* @param non-empty-string|BaseJwt\Token $jwt JWT string or instance of Token
* @throws InvalidConfigException
* @since 3.0.0
*/
public function validate($jwt): bool
{
$configuration = $this->getConfiguration();
$token = $jwt instanceof Token ? $jwt : $this->parse($jwt);
$token = $jwt instanceof BaseJwt\Token ? $jwt : $this->parse($jwt);
$constraints = $this->prepareValidationConstraints();

return $configuration->validator()->validate($token, ...$constraints);
}

/**
* @return Validation\Constraint[]
* @return BaseJwt\Validation\Constraint[]
* @throws InvalidConfigException
*/
protected function prepareValidationConstraints(): array
{
$configuredConstraints = $this->getConfiguration()->validationConstraints();
if (\count($configuredConstraints)) {
if (!empty($configuredConstraints)) {
return $configuredConstraints;
}

Expand Down
32 changes: 14 additions & 18 deletions src/JwtHttpBearerAuth.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@
use yii\base\InvalidConfigException;
use yii\di\Instance;
use yii\filters\auth\HttpBearerAuth;
use yii\web\IdentityInterface;
use yii\web\Request;
use yii\web\Response;
use yii\web\UnauthorizedHttpException;
use yii\web\User;
use yii\web;

/**
* JwtHttpBearerAuth is an action filter that supports the authentication method based on HTTP Bearer JSON Web Token.
Expand All @@ -32,7 +28,7 @@
* }
* ```
*
* @author Paweł Bizley Brzozowski <pawel@positive.codes> since 2.0 (fork)
* @author Paweł Bizley Brzozowski <pawel[email protected]> since 2.0 (fork)
* @author Dmitriy Demin <[email protected]> original package
*/
class JwtHttpBearerAuth extends HttpBearerAuth
Expand Down Expand Up @@ -91,20 +87,20 @@ public function getJwtComponent(): Jwt|JwtTools

/**
* Authenticates the current user.
* @param User $user
* @param Request $request
* @param Response $response
* @return IdentityInterface|null the authenticated user identity. If authentication information is not provided, null will be returned.
* @param web\User $user
* @param web\Request $request
* @param web\Response $response
* @return web\IdentityInterface|null the authenticated user identity. If authentication information is not provided, null will be returned.
* @throws InvalidConfigException When JWT configuration has not been properly initialized.
* @throws CannotDecodeContent When something goes wrong while decoding token.
* @throws Token\InvalidTokenStructure When token string structure is invalid.
* @throws Token\UnsupportedHeaderFound When parsed token has an unsupported header.
* @throws Validation\RequiredConstraintsViolated When constraint is not present in token.
* @throws Validation\NoConstraintsGiven When no constraints are provided.
* @throws Validation\ConstraintViolation When constraint is violated.
* @throws UnauthorizedHttpException if authentication information is provided but is invalid.
* @throws web\UnauthorizedHttpException if authentication information is provided but is invalid.
*/
public function authenticate($user, $request, $response): ?IdentityInterface // BC signature
public function authenticate($user, $request, $response): ?web\IdentityInterface // BC signature
{
/** @var string|null $authHeader */
$authHeader = $request->getHeaders()->get($this->header);
Expand Down Expand Up @@ -137,7 +133,7 @@ public function authenticate($user, $request, $response): ?IdentityInterface //
}
}

if (!$identity instanceof IdentityInterface) {
if (!$identity instanceof web\IdentityInterface) {
return null;
}

Expand All @@ -157,21 +153,21 @@ public function processToken(string $data): ?Token
}

/**
* @throws UnauthorizedHttpException
* @throws web\UnauthorizedHttpException
*/
public function fail(Response $response): void
public function fail(web\Response $response): void
{
$this->challenge($response);
$this->handleFailure($response);
}

/**
* Handles authentication failure.
* @param Response $response
* @throws UnauthorizedHttpException
* @param web\Response $response
* @throws web\UnauthorizedHttpException
*/
public function handleFailure($response): void // BC signature
{
throw new UnauthorizedHttpException('Your request was made with invalid or expired JSON Web Token.');
throw new web\UnauthorizedHttpException('Your request was made with invalid or expired JSON Web Token.');
}
}
Loading

0 comments on commit 42cdaf3

Please sign in to comment.