Auth0\SDK\JWTVerifier::verifyAndDecode PHP Метод

verifyAndDecode() публичный Метод

public verifyAndDecode ( $jwt )
    public function verifyAndDecode($jwt)
    {
        $tks = explode('.', $jwt);
        if (count($tks) != 3) {
            throw new InvalidTokenException('Wrong number of segments');
        }
        $headb64 = $tks[0];
        $body64 = $tks[1];
        $head = json_decode(JWT::urlsafeB64Decode($headb64));
        if (!is_object($head) || !isset($head->alg)) {
            throw new InvalidTokenException("Invalid token");
        }
        if (!in_array($head->alg, $this->suported_algs)) {
            throw new InvalidTokenException("Invalid signature algorithm");
        }
        if ($head->alg === 'RS256') {
            $body = json_decode(JWT::urlsafeB64Decode($body64));
            if (!in_array($body->iss, $this->authorized_iss)) {
                throw new CoreException("We can't trust on a token issued by: `{$body->iss}`.");
            }
            $secret = $this->JWKFetcher->fetchKeys($body->iss);
        } elseif ($head->alg === 'HS256') {
            if ($this->secret_base64_encoded) {
                $secret = JWT::urlsafeB64Decode($this->client_secret);
            } else {
                $secret = $this->client_secret;
            }
        } else {
            throw new InvalidTokenException("Invalid signature algorithm");
        }
        try {
            // Decode the user
            $decodedToken = JWT::decode($jwt, $secret, array('HS256', 'RS256'));
            // validate that this JWT was made for us
            $audience = $decodedToken->aud;
            if (!is_array($audience)) {
                $audience = [$audience];
            }
            if (count(array_intersect($audience, $this->valid_audiences)) == 0) {
                throw new InvalidTokenException("This token is not intended for us.");
            }
        } catch (\Exception $e) {
            throw new CoreException($e->getMessage());
        }
        return $decodedToken;
    }

Usage Example

Пример #1
0
 public function testTokenWithNotEncodedSecret()
 {
     $client_id = 'client_id_1';
     $client_secret = 'client_secret_1';
     $generator = new TokenGenerator(['client_id' => $client_id, 'client_secret' => $client_secret, 'secret_base64_encoded' => false]);
     $jwt = $generator->generate(['users' => ['actions' => ['read']]]);
     $verifier = new JWTVerifier(['valid_audiences' => [$client_id], 'client_secret' => $client_secret, 'secret_base64_encoded' => false]);
     $decoded = $verifier->verifyAndDecode($jwt);
     $this->assertObjectHasAttribute('aud', $decoded);
     $this->assertEquals($client_id, $decoded->aud);
     $this->assertObjectHasAttribute('scopes', $decoded);
     $this->assertObjectHasAttribute('users', $decoded->scopes);
     $this->assertObjectHasAttribute('actions', $decoded->scopes->users);
     $this->assertArraySubset(['read'], $decoded->scopes->users->actions);
 }