php-simple-jwt/src/Validator/JWTValidator.php

84 lines
2.1 KiB
PHP
Raw Normal View History

2021-02-11 12:22:51 +00:00
<?php
2023-04-09 00:40:21 +00:00
namespace NoccyLabs\SimpleJWT\Validator;
2021-02-11 12:22:51 +00:00
2023-04-09 00:40:21 +00:00
use NoccyLabs\SimpleJWT\JWTToken;
use NoccyLabs\SimpleJWT\Key\KeyInterface;
2021-02-11 12:22:51 +00:00
2023-04-09 00:40:21 +00:00
class JWTValidator
2021-02-11 12:22:51 +00:00
{
private $requireHeaders = [];
private $requireClaims = [];
private $requireIssuer = [];
private $requireAudience = [];
2021-02-11 12:22:51 +00:00
public function __construct()
{
$this->requireHeaders = [
'alg',
'typ',
];
}
public function addRequiredClaim(string $name)
{
if (!in_array($name, $this->requireClaims)) {
return;
}
$this->requireClaims[] = $name;
2021-02-11 12:22:51 +00:00
}
public function requireIssuer($issuer)
{
$this->requireIssuer = (array)$issuer;
}
public function requireAudience($audience)
{
$this->requireAudience = (array)$audience;
}
2023-04-09 00:40:21 +00:00
public function validateToken(JWTToken $token)
2021-02-11 12:22:51 +00:00
{
if (!$token->isValid()) {
2023-04-09 00:40:21 +00:00
throw new JWTTokenException("The token is not valid");
2021-02-11 12:22:51 +00:00
}
if (!$token->header->hasAll($this->requireHeaders)) {
2023-04-09 00:40:21 +00:00
throw new JWTHeaderException("The token is missing one or more required headers");
2021-02-11 12:22:51 +00:00
}
if (!$token->claims->hasAll($this->requireClaims)) {
2023-04-09 00:40:21 +00:00
throw new JWTHeaderException("The token is missing one or more required claims");
2021-02-11 12:22:51 +00:00
}
if ($this->requireIssuer) {
$hasIssuer = $token->header->has("iss");
if ((!$hasIssuer)
|| (!in_array($token->header->get("iss"), $this->requireIssuer)))
2023-04-09 00:40:21 +00:00
throw new JWTTokenException("Invalid issuer");
}
if ($this->requireAudience) {
$hasAudience = $token->header->has("aud");
if ((!$hasAudience)
|| (!in_array($token->header->get("aud"), $this->requireAudience)))
2023-04-09 00:40:21 +00:00
throw new JWTTokenException("Invalid audience");
}
2021-02-11 12:22:51 +00:00
return true;
}
public function validate(KeyInterface $key, string $raw)
{
2023-04-09 00:40:21 +00:00
$token = new JWTToken($key, $raw);
2021-02-11 12:22:51 +00:00
if ($this->validateToken($token)) {
return $token;
}
}
}