* Removed the addRequiredClaimWithValue() method, as checking the value should be up to the implementation.
		
			
				
	
	
		
			56 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			56 lines
		
	
	
		
			1.2 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
<?php
 | 
						|
 | 
						|
namespace NoccyLabs\SimpleJwt\Validator;
 | 
						|
 | 
						|
use NoccyLabs\SimpleJwt\JwtToken;
 | 
						|
use NoccyLabs\SimpleJwt\Key\KeyInterface;
 | 
						|
 | 
						|
class JwtValidator
 | 
						|
{
 | 
						|
    private $requireHeaders = [];
 | 
						|
 | 
						|
    private $requireClaims = [];
 | 
						|
 | 
						|
    public function __construct()
 | 
						|
    {
 | 
						|
        $this->requireHeaders = [
 | 
						|
            'alg',
 | 
						|
            'typ',
 | 
						|
        ];
 | 
						|
    }
 | 
						|
 | 
						|
    public function addRequiredClaim(string $name)
 | 
						|
    {
 | 
						|
        if (!in_array($name, $this->requireClaims)) {
 | 
						|
            return;
 | 
						|
        }
 | 
						|
        $this->requireClaims[] = $name;
 | 
						|
    }
 | 
						|
 | 
						|
    public function validateToken(JwtToken $token)
 | 
						|
    {
 | 
						|
        if (!$token->isValid()) {
 | 
						|
            throw new JwtTokenException("The token is not valid");
 | 
						|
        }
 | 
						|
 | 
						|
        if (!$token->header->hasAll($this->requireHeaders)) {
 | 
						|
            throw new JwtHeaderException("The token is missing one or more required headers");
 | 
						|
        }
 | 
						|
 | 
						|
        if (!$token->claims->hasAll($this->requireClaims)) {
 | 
						|
            throw new JwtHeaderException("The token is missing one or more required claims");
 | 
						|
        }
 | 
						|
 | 
						|
        return true;
 | 
						|
    }
 | 
						|
 | 
						|
    public function validate(KeyInterface $key, string $raw)
 | 
						|
    {
 | 
						|
        $token = new JwtToken($key, $raw);
 | 
						|
        if ($this->validateToken($token)) {
 | 
						|
            return $token;
 | 
						|
        }
 | 
						|
    }
 | 
						|
}
 | 
						|
 |