Since: 2.0.0
Author: Luís Otávio Cobucci Oblonczyk (lcobucci@gmail.com)
 /**
  * {@inheritdoc}
  */
 public function validateAuthorization(\Phalcon\Http\RequestInterface $request)
 {
     if (!$request->getHeader('authorization')) {
         throw OAuthServerException::accessDenied('Missing "Authorization" header');
     }
     $header = $request->getHeader('authorization');
     $jwt = trim(preg_replace('/^(?:\\s+)?Bearer\\s/', '', $header));
     try {
         // Attempt to parse and validate the JWT
         $token = (new Parser())->parse($jwt);
         if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) {
             throw OAuthServerException::accessDenied('Access token could not be verified');
         }
         // Ensure access token hasn't expired
         $data = new ValidationData();
         $data->setCurrentTime(time());
         if ($token->validate($data) === false) {
             throw OAuthServerException::accessDenied('Access token is invalid');
         }
         // Check if token has been revoked
         if ($this->accessTokenRepository->isAccessTokenRevoked($token->getClaim('jti'))) {
             throw OAuthServerException::accessDenied('Access token has been revoked');
         }
         // Return the response with additional attributes
         $response = ['oauth_access_token_id' => $token->getClaim('jti'), 'oauth_client_id' => $token->getClaim('aud'), 'oauth_user_id' => $token->getClaim('sub'), 'oauth_scopes' => $token->getClaim('scopes')];
         return $response;
     } catch (\InvalidArgumentException $exception) {
         // JWT couldn't be parsed so return the request as is
         throw OAuthServerException::accessDenied($exception->getMessage());
     }
 }
Beispiel #2
0
 /**
  * @test
  *
  * @uses Lcobucci\JWT\Claim\Basic::__construct
  * @uses Lcobucci\JWT\Claim\Basic::getName
  * @uses Lcobucci\JWT\Claim\Basic::getValue
  * @uses Lcobucci\JWT\ValidationData::__construct
  * @uses Lcobucci\JWT\ValidationData::setIssuer
  * @uses Lcobucci\JWT\ValidationData::has
  * @uses Lcobucci\JWT\ValidationData::get
  *
  * @covers Lcobucci\JWT\Claim\EqualsTo::validate
  */
 public function validateShouldReturnFalseWhenValueIsNotEqualsToValidationData()
 {
     $claim = new EqualsTo('iss', 'test');
     $data = new ValidationData();
     $data->setIssuer('test1');
     $this->assertFalse($claim->validate($data));
 }
 /**
  * @param Application $app
  */
 public function register(Application $app)
 {
     $app['jwt.builder'] = $app->share(function (Application $app) {
         $builder = new Builder();
         $builder->setIssuer($app['config']['jwt']['iss']);
         return $builder;
     });
     $app['jwt.signer'] = $app->share(function () {
         return new Sha256();
     });
     $app['jwt.keys.private'] = $app->share(function (Application $app) {
         $file = __DIR__ . '/../../' . $app['config']['jwt']['keys']['private']['file'];
         return new Key('file://' . $file, $app['config']['jwt']['keys']['private']['passphrase']);
     });
     $app['jwt.keys.public'] = $app->share(function (Application $app) {
         $file = __DIR__ . '/../../' . $app['config']['jwt']['keys']['public']['file'];
         return new Key('file://' . $file);
     });
     $app['jwt.validation_data'] = $app->share(function (Application $app) {
         $data = new ValidationData();
         $data->setIssuer($app['config']['jwt']['iss']);
         return $data;
     });
     $app['jwt.encoder'] = $app->share(function (Application $app) {
         return new JwtEncoderService($app['jwt.builder'], $app['jwt.signer'], $app['jwt.keys.private'], $app['clock'], new Integer($app['config']['jwt']['exp']), new Integer($app['config']['jwt']['nbf']));
     });
     $app['jwt.decoder'] = $app->share(function (Application $app) {
         return new JwtDecoderService(new Parser(), $app['jwt.validation_data'], $app['jwt.signer'], $app['jwt.keys.public']);
     });
 }
Beispiel #4
0
 /**
  * {@inheritdoc}
  */
 public function validate(ValidationData $data)
 {
     if ($data->has($this->getName())) {
         return $this->getValue() === $data->get($this->getName());
     }
     return true;
 }
 /**
  * Get the current user.
  *
  * Will prefer the static user cache over sessions. The static user
  * cache is primarily used for stateless authentication. For stateful authentication,
  * cookies + sessions will be used.
  *
  * @param string $key field to retrieve. Leave null to get entire User record
  * @return array|null User record. or null if no user is logged in.
  * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
  */
 public static function user($key = null)
 {
     $user = array();
     $request = new CakeRequest();
     if (($authorization = $request->header('Authorization')) && preg_match('/^Bearer (.*?)$/', $authorization, $matches)) {
         $signer = new Sha256();
         $token = (new Parser())->parse((string) next($matches));
         try {
             if ($token->verify($signer, Configure::read('Security.salt'))) {
                 $data = new ValidationData(Configure::read('Security.timeout') > 0 ? null : $token->getClaim('iat'));
                 $data->setIssuer(Router::url('/', true));
                 $data->setAudience($request->clientIp());
                 if ($token->validate($data)) {
                     if ($user = json_decode($token->getClaim('data'), true)) {
                         if (!empty($user['id'])) {
                             if (!empty(static::$_user) && static::$_user['id'] == $user['id']) {
                                 $user = static::$_user;
                                 return empty($key) ? $user : Hash::get($user, $key);
                             } else {
                                 $User = ClassRegistry::init('User');
                                 $User->id = $user['id'];
                                 return Hash::get($User->read(), 'User' . (empty($key) ? '' : '.' . $key));
                             }
                         }
                     }
                 }
             }
         } catch (Exception $ex) {
         }
     }
     return false;
 }
 public function validateJwtToken($token = null)
 {
     if (is_null($token)) {
         return false;
     }
     $token = str_replace('Bearer ', '', $token);
     $token = (new Parser())->parse($token);
     $signer = new Sha256();
     // Verifica se a chave do token corresponde com a chave da aplicacao
     if (!$token->verify($signer, 'minicurso_conference.api.signature')) {
         return false;
     }
     $validation = new ValidationData();
     $validation->setIssuer('http://minicurso_conference.api');
     $validation->setAudience('http://minicurso_conference.api');
     // Verifica se o token eh valido
     $isValid = $token->validate($validation);
     if (!$isValid) {
         return false;
     }
     // Verifica se o token precisa ser recriado. O tempo verificacao eh de um dia
     $validation->setCurrentTime(time() + 86400);
     $needRegenerate = !$token->validate($validation);
     if ($needRegenerate) {
         return JWTTokenGenerator::generate();
     }
     return $token;
 }
Beispiel #7
0
 public function checkCallbackSignature($token, $tokenId)
 {
     try {
         $parser = new Parser();
         $token = $parser->parse((string) $token);
     } catch (\RuntimeException $exception) {
         throw new Exception\InvalidToken();
     }
     $validation = new ValidationData();
     $validation->setIssuer($this->gatewayUrl);
     $validation->setAudience($this->key);
     $validation->setId($tokenId);
     if (!$token->validate($validation)) {
         throw new Exception\TokenValidationFailed();
     }
     if (!$token->verify(new Sha256(), $this->secret)) {
         throw new Exception\TokenVerificationFailed();
     }
     if (!$token->hasClaim('sub')) {
         throw new Exception\SubjectClaimMissing();
     }
     $this->username = $token->getClaim('sub');
     if (!$token->hasClaim('pass')) {
         throw new Exception\PassClaimMissing();
     }
     $this->pass = $token->getClaim('pass');
 }
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     $token = $request->header('access-token');
     $token = isset($token) ? $request->header('access-token') : $request->get('api_token');
     if (!$token) {
         return response('Unauthorized.', 403);
     }
     $key = getenv('APP_KEY');
     $signer = new Sha256();
     $data = new ValidationData();
     // It will use the current time to validate (iat, nbf and exp)
     $data->setIssuer($request->server('REMOTE_ADDR'));
     $data->setAudience($request->server('HTTP_HOST'));
     try {
         $token = (new Parser())->parse((string) $token);
         if (!$token->validate($data)) {
             return response('Unauthorized data', 401);
         }
         if (!$token->verify($signer, $key)) {
             return response('Unauthorized sign', 401);
         }
         putenv("USER=" . $token->getClaim('uid'));
         return $next($request);
     } catch (\Exception $e) {
         return response('Unauthorized: ' . $e->getMessage(), 403);
     }
 }
Beispiel #9
0
 /**
  * {@inheritdoc}
  */
 public function validate(ValidationData $data) : bool
 {
     if ($data->has($this->getName())) {
         return in_array($data->get($this->getName()), $this->getValue());
     }
     return true;
 }
Beispiel #10
0
 /**
  * @test
  *
  * @uses \Lcobucci\JWT\Claim\Basic
  * @uses \Lcobucci\JWT\ValidationData
  *
  * @covers \Lcobucci\JWT\Claim\EqualsTo::validate
  */
 public function validateShouldReturnFalseWhenValueIsNotEqualsToValidationData()
 {
     $claim = new EqualsTo('sub', 'test');
     $data = new ValidationData();
     $data->setSubject('test1');
     self::assertFalse($claim->validate($data));
 }
Beispiel #11
0
 /**
  * @test
  *
  * @uses \Lcobucci\JWT\Claim\Basic
  * @uses \Lcobucci\JWT\ValidationData
  *
  * @covers \Lcobucci\JWT\Claim\ContainsEqualsTo::validate
  */
 public function validateShouldReturnFalseWhenValidationDataValueIsNotContained()
 {
     $claim = new ContainsEqualsTo('aud', ['test', 'test2']);
     $data = new ValidationData();
     $data->setAudience('test3');
     self::assertFalse($claim->validate($data));
 }
Beispiel #12
0
 /**
  * @test
  *
  * @uses \Lcobucci\JWT\Claim\Basic
  * @uses \Lcobucci\JWT\ValidationData
  *
  * @covers \Lcobucci\JWT\Claim\ContainedEqualsTo::validate
  */
 public function validateShouldReturnFalseWhenClaimValueIsNotEqualToAtLeastOneItemInValidationData()
 {
     $claim = new ContainedEqualsTo('iss', 'test');
     $data = new ValidationData();
     $data->setIssuer(['test2', 'test3']);
     self::assertFalse($claim->validate($data));
 }
Beispiel #13
0
 /**
  * TokenValidator constructor.
  * @param ValidationData $validationData
  * @param Signer $signer
  * @param string $secret
  * @param array $config
  */
 public function __construct(ValidationData $validationData, Signer $signer, string $secret, array $config)
 {
     $this->validationData = $validationData;
     $this->signer = $signer;
     $this->secret = $secret;
     $this->validationData->setAudience($config['audience']);
     $this->validationData->setIssuer($config['issuer']);
     $this->validationData->setId($config['appid']);
 }
Beispiel #14
0
 /**
  * validate token
  *
  * @param  [string] $tokenString
  * @param  [string] $socketId
  * @return [boolean]
  */
 private function validateToken($tokenString)
 {
     //
     $parser = new Parser();
     // data of validator
     // add time for experitation
     $validatorData = new ValidationData();
     $validatorData->setCurrentTime(time());
     // getting token for JWT
     $token = $parser->parse((string) $tokenString);
     return $token->validate($validatorData);
 }
 public function validateData()
 {
     $validationData = new ValidationData();
     // It will use the current time to validate (iat, nbf and exp)
     //$this->log('JwtTokenAuthenticate -> Validating token...');
     $validationData->setIssuer($this->_serverName);
     $validationData->setAudience($this->_serverName);
     // WARN: Here it's better to see if the client is the right one
     //$validationData->setId(15); // WARN (the last about this LOL): here you're validating if the Parser done his job
     //$validationData->setSigner(strval(Configure::read('Security.cipherSeed'))); Signature verification and token validation are different things
     //$validationData->setCurrentTime(time() + 16); // ERR: this shouldn't be called
     return $validationData;
 }
 public function findUserByTokenOrFail($token)
 {
     $parsedToken = $this->getParsedToken($token);
     $userClass = app('config')->get('laravel-jwt.model');
     $user = app($userClass)->findByQualifiedKeyForToken($this->getData($parsedToken, 'id'));
     if (!$user) {
         throw new UserNotFoundException();
     }
     $userHash = $this->generateHashForUser($user, $this->getData($parsedToken, 'iat'));
     $validationData = new ValidationData();
     $validationData->setIssuer(app('config')->get('laravel-jwt.issuer'));
     $validationData->setId($userHash);
     if ($parsedToken->validate($validationData)) {
         return $user;
     }
     throw new UserNotFoundException();
 }
 /**
  * Handle an incoming reques And verify if token exists and is valid
  *
  * @param  \Illuminate\Http\Request $request
  * @param  \Closure $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     $token = $request->header('access-token');
     $token = isset($token) ? $request->header('access-token') : $request->get('access-token');
     if (!$token) {
         return response('Unauthorized.', 403);
     }
     $key = config('jwt.key');
     $signer = new Sha256();
     $data = new ValidationData();
     // It will use the current time to validate (iat, nbf and exp)
     $data->setIssuer(config('jwt.host'));
     $data->setAudience($request->server('REMOTE_ADDR'));
     try {
         $token = (new Parser())->parse((string) $token);
         if (!$token->validate($data)) {
             return response('Unauthorized data', 401);
         }
         if (!$token->verify($signer, $key)) {
             return response('Unauthorized sign', 401);
         }
         putenv("USER="******"TOKEN", $token->__toString()));
         return $response;
     }
     $newToken = (new Builder())->setIssuer(config('jwt.host'))->setAudience($request->server('REMOTE_ADDR'))->setIssuedAt($time)->setNotBefore($time)->setExpiration($time + 3600)->set('uid', getenv('USER'))->sign($signer, $key)->getToken();
     $response->withCookie(new Cookie("TOKEN", $newToken->__toString()));
     return $response;
 }
 /**
  * @param Application $app
  */
 public function register(Application $app)
 {
     $app['security.authentication_listener.factory.jwt'] = $app->protect(function ($name, $options) use($app) {
         $app['security.validation_data.' . $name . '.jwt'] = $app->share(function () use($options) {
             $validationData = new ValidationData();
             $claims = isset($options['validation']) ? $options['validation'] : [];
             foreach ($claims as $claim => $value) {
                 switch ($claim) {
                     case 'jti':
                         $validationData->setId($value);
                         break;
                     case 'iss':
                         $validationData->setIssuer($value);
                         break;
                     case 'aud':
                         $validationData->setAudience($value);
                         break;
                     case 'sub':
                         $validationData->setSubject($value);
                         break;
                     case 'current_time':
                         $validationData->setCurrentTime($value);
                         break;
                 }
             }
             return $validationData;
         });
         $app['security.public_key.' . $name . '.jwt'] = $app->share(function () use($options) {
             return new Key($options['public_key']);
         });
         $app['security.token_decoder.' . $name . '.jwt'] = $app->share(function (Application $app) use($name, $options) {
             return new JwtDecoderService(new Parser(), $app['security.validation_data.' . $name . '.jwt'], new Sha256(), $app['security.public_key.' . $name . '.jwt'], $options['required_claims']);
         });
         // define the authentication provider object
         $app['security.authentication_provider.' . $name . '.jwt'] = $app->share(function () use($app, $name) {
             return new JwtAuthenticationProvider($app['security.token_decoder.' . $name . '.jwt']);
         });
         // define the authentication listener object
         $app['security.authentication_listener.' . $name . '.jwt'] = $app->share(function () use($app, $name) {
             return new JwtListener($app['security.token_storage'], $app['security.authentication_manager'], $app['security.token_decoder.' . $name . '.jwt']);
         });
         return ['security.authentication_provider.' . $name . '.jwt', 'security.authentication_listener.' . $name . '.jwt', null, 'pre_auth'];
     });
 }
 public function setUp()
 {
     $this->publicKeyString = file_get_contents(__DIR__ . '/samples/public.pem');
     $this->tokenString = rtrim(file_get_contents(__DIR__ . '/samples/token.txt'), '\\r\\n');
     $this->tokenHeaders = ["typ" => "JWT", "alg" => "RS256"];
     $this->tokenClaims = ["uid" => "1", "nick" => "foo", "email" => "*****@*****.**", "iss" => "http://culudb-jwt-provider.dev", "iat" => "1461829061", "exp" => "1461829061", "nbf" => "1461829061"];
     $this->tokenClaimsAsValueObjects = ["uid" => new Basic('uid', '1'), "nick" => new Basic('nick', 'foo'), "email" => new Basic('email', '*****@*****.**'), "iss" => new EqualsTo('iss', 'http://culudb-jwt-provider.dev'), "iat" => new LesserOrEqualsTo('iat', '1461829061'), "exp" => new GreaterOrEqualsTo('exp', '1461829061'), "nbf" => new LesserOrEqualsTo('nbf', '1461829061')];
     $this->payload = explode('.', $this->tokenString);
     $decoder = new Decoder();
     $hash = $decoder->base64UrlDecode($this->payload[2]);
     $this->signature = new Signature($hash);
     $this->token = new Jwt($this->tokenHeaders, $this->tokenClaimsAsValueObjects, $this->signature, $this->payload);
     $this->parser = new Parser();
     $this->validationData = new ValidationData();
     $this->validationData->setIssuer("http://culudb-jwt-provider.dev");
     $this->signer = new Sha256();
     $this->publicKey = new Key($this->publicKeyString);
     $this->requiredCLaims = ['uid', 'nick', 'email'];
     $this->decoderService = new JwtDecoderService($this->parser, $this->validationData, $this->signer, $this->publicKey, $this->requiredCLaims);
 }
Beispiel #20
0
 public static function validateToken($token)
 {
     $data = new ValidationData();
     // It will use the current time to validate (iat, nbf and exp)
     $data->setIssuer('http://testify.com');
     $data->setAudience('http://testify.com');
     //$data->setId('4f1g23a12aa');
     if ($token->validate($data)) {
         return true;
     } else {
         return false;
     }
 }
 public function invalidValidationData()
 {
     $expired = new ValidationData(self::CURRENT_TIME + 3020);
     $expired->setAudience('http://client.abc.com');
     $expired->setIssuer('http://api.abc.com');
     $invalidAudience = new ValidationData(self::CURRENT_TIME - 10);
     $invalidAudience->setAudience('http://cclient.abc.com');
     $invalidAudience->setIssuer('http://api.abc.com');
     $invalidIssuer = new ValidationData(self::CURRENT_TIME - 10);
     $invalidIssuer->setAudience('http://client.abc.com');
     $invalidIssuer->setIssuer('http://aapi.abc.com');
     return [[$expired], [$invalidAudience], [$invalidIssuer]];
 }
Beispiel #22
0
 /**
  * Validates token for cookie and returns values if valid
  *
  * @param string $token
  *
  * @return array
  */
 protected function parseAndValidateToken(string $token)
 {
     try {
         $token = (new Parser())->parse($token);
         // @todo How to test: It will use the current time to validate (iat, nbf and exp)
         $data = new ValidationData();
         $data->setIssuer(self::ISSUER);
         $values = [];
         if ($token->validate($data) && $token->verify(new Sha256(), $this->configuration->get('Cookie.Signer.Key'))) {
             /**
              * @var Claim $claim
              */
             $ignored = array_fill_keys(['iss', 'exp'], true);
             foreach ($token->getClaims() as $claim) {
                 if (isset($ignored[$claim->getName()])) {
                     continue;
                 }
                 $values[$claim->getName()] = $claim->getValue();
             }
         }
         return $values;
     } catch (\InvalidArgumentException $e) {
         return [];
     }
 }
Beispiel #23
0
 /**
  * @test
  *
  * @uses Lcobucci\JWT\Claim\Basic::__construct
  * @uses Lcobucci\JWT\Claim\Basic::getName
  * @uses Lcobucci\JWT\Claim\Basic::getValue
  * @uses Lcobucci\JWT\ValidationData::__construct
  * @uses Lcobucci\JWT\ValidationData::setIssuer
  * @uses Lcobucci\JWT\ValidationData::has
  * @uses Lcobucci\JWT\ValidationData::get
  *
  * @covers Lcobucci\JWT\Claim\GreaterOrEqualsTo::validate
  */
 public function validateShouldReturnFalseWhenValueIsLesserThanValidationData()
 {
     $claim = new GreaterOrEqualsTo('iss', 10);
     $data = new ValidationData();
     $data->setIssuer(11);
     $this->assertFalse($claim->validate($data));
 }
Beispiel #24
0
 /**
  * Returns Builder/ValidationData with "iss" and "aud" claims set.
  *
  * @param Builder|ValidationData $object
  * @param string $issuer
  * @param string $audience
  *
  * @return Builder|ValidationData
  */
 private function initClaims($object, $issuer = null, $audience = null)
 {
     if ($object instanceof Builder) {
         $object->setIssuer(isset($issuer) ? $issuer : \Yii::$app->getRequest()->getHostInfo());
     }
     $object->setAudience(isset($audience) ? $audience : $this->getAudience());
     return $object;
 }
Beispiel #25
0
         if ($u) {
             $this->db->setUser($u->getId());
             $this->db->addLog('get_api', 'GET', $request->getAttribute('ip_address'));
             $response = $next($request, $response);
             return $response;
         } else {
             $msg = "Wrong key supplied";
         }
     }
     // Post Requests: JWT Token Required
     if ($request->isPost() || $request->isPut() || $request->isDelete()) {
         $signer = new Sha256();
         $token = (new Parser())->parse((string) $apikey);
         // Parses from a string
         $u = $this->db->getUsers()->findPk((int) $token->getClaim('uid'));
         $data = new ValidationData();
         // It will use the current time to validate (iat, nbf and exp)
         $data->setIssuer($_SERVER['HTTP_HOST']);
         $data->setAudience($_SERVER['HTTP_HOST']);
         if ($u && $token->verify($signer, $u->GetRwapikey()) && $token->validate($data)) {
             $this->db->setUser($u->getId());
             $this->db->addLog('post_api', 'POST', $request->getAttribute('ip_address'));
             $response = $next($request, $response);
             return $response;
         } else {
             $msg = "Wrong key supplied";
         }
     }
 } else {
     if ($request->isPost() && $route->getPattern() == "/api/login") {
         $response = $next($request, $response);
Beispiel #26
0
 public function authenticate()
 {
     // parse response
     $code = null;
     $state = null;
     if (isset($_GET['error'])) {
         throw new \Exception('Response from Authorization Server: ' . $_GET['error']);
     }
     if (isset($_GET['code'])) {
         $code = $_GET['code'];
     }
     if (isset($_GET['state'])) {
         $state = $_GET['state'];
     }
     $existingState = $this->getStateSession();
     if ($existingState !== $state) {
         throw new \Exception('Broken authorization flow - state mismatch');
     }
     if ($code === null) {
         throw new \Exception('"code" param has not been received from Authorization Server');
     }
     $authorizationCode = $this->requestTokens($code);
     if (isset($authorizationCode->error)) {
         throw new \Exception($authorizationCode->error_description);
     }
     if (!isset($authorizationCode->id_token)) {
         throw new \Exception('id_token has not been received from Authorization Server');
     }
     $tmpimpl = count(explode('.', $authorizationCode->id_token));
     if ($tmpimpl != 3 && $tmpimpl != 5) {
         throw new \Exception('Incorrect id_token received from Authorization Server');
     }
     if ($tmpimpl == 5) {
         throw new \Exception('Encrypted JWT is not supported yet');
     }
     $parser = new Lcobucci\JWT\Parser();
     $token = $parser->parse($authorizationCode->id_token);
     $alg = $token->getHeader('alg');
     if ($alg !== 'RS256') {
         throw new \Exception('Only alg RS256 is accepted');
     }
     $kid = $token->getHeader('kid');
     $validationData = new Lcobucci\JWT\ValidationData();
     $validationData->setIssuer($this->getProviderURL());
     $validationData->setAudience($this->clientID);
     $isValidToken = $token->validate($validationData);
     if (!$isValidToken) {
         throw new \Exception('Received "id_token" is not valid - propbably expired');
     }
     // verify sig
     $jwks_uri = $this->getOPConfigValue('jwks_uri');
     $jwks_body = $this->runHttpRequest($jwks_uri);
     $this->jwks = json_decode($jwks_body, true);
     if (!is_array($this->jwks) || !array_key_exists('keys', $this->jwks)) {
         throw new \Exception('JWKS not found, cannot verify signature');
     }
     $keyVer = null;
     foreach ($this->jwks['keys'] as $key => $val) {
         if ($val['kid'] === $kid && $val['use'] === 'sig') {
             $keyVer = $this->jwks['keys'][$key];
             break;
         }
     }
     if ($keyVer === null) {
         throw new \Exception('JWK not found, cannot verify signature');
     }
     $jwkObj = new Jwk($keyVer);
     $signer = new Lcobucci\JWT\Signer\Rsa\Sha256();
     $keychain = new Lcobucci\JWT\Signer\Keychain();
     $sigValid = $token->verify($signer, $keychain->getPublicKey($jwkObj->toKey()));
     if ($sigValid !== true) {
         throw new \Exception('Received "id_token" is not valid. Signature validation failed');
     }
     /**
      * @var Lcobucci\JWT\Claim\Basic[] $claimsObj
      */
     $claimsObj = $token->getClaims();
     $claims = array();
     foreach ($claimsObj as $cl) {
         if ($cl instanceof Lcobucci\JWT\Claim\Basic) {
             $claims['' . $cl->getName() . ''] = $cl->getValue();
         }
     }
     $claims['iss'] = $token->getClaim('iss');
     unset($_SESSION['joidc_once']);
     unset($_SESSION['joidc_state']);
     unset($_SESSION['joidc_issuer']);
     return $claims;
 }
Beispiel #27
0
 /**
  * @test
  *
  * @uses Lcobucci\JWT\Token::__construct
  * @uses Lcobucci\JWT\ValidationData
  * @uses Lcobucci\JWT\Claim\Basic
  * @uses Lcobucci\JWT\Claim\EqualsTo
  * @uses Lcobucci\JWT\Claim\LesserOrEqualsTo
  * @uses Lcobucci\JWT\Claim\GreaterOrEqualsTo
  *
  * @covers Lcobucci\JWT\Token::validate
  * @covers Lcobucci\JWT\Token::getValidatableClaims
  */
 public function validateShouldReturnTrueWhenThereAreNoFailedValidatableClaims()
 {
     $now = time();
     $token = new Token([], ['iss' => new EqualsTo('iss', 'test'), 'iat' => new LesserOrEqualsTo('iat', $now), 'exp' => new GreaterOrEqualsTo('ext', $now + 500), 'testing' => new Basic('testing', 'test')]);
     $data = new ValidationData($now + 10);
     $data->setIssuer('test');
     $this->assertTrue($token->validate($data));
 }
Beispiel #28
0
 public function checkToken($token)
 {
     $fprikey = $this->app['BASE_DIR'] . "/app/config/key/private.pkey";
     $fpubkey = $this->app['BASE_DIR'] . "/app/config/key/public.pkey";
     if (!file_exists($fpubkey) || !file_exists($fprikey)) {
         throw new \Exception('Chaves não configuradas!!!', 500);
     }
     $tkon = (new Parser())->parse((string) $token);
     $uid = $tkon->getClaim('jti');
     $data = new ValidationData();
     // It will use the current time to validate (iat, nbf and exp)
     $data->setIssuer($_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']);
     $data->setId($uid);
     if (!$tkon->validate($data)) {
         $this->logout();
         throw new \Exception(_("Credentials incorrect"), 403);
     }
     $sign = new Sha512();
     $publicKey = new Key("file://" . $fpubkey);
     if (!$tkon->verify($sign, $publicKey)) {
         throw new \Exception(_("Credentials incorrect"), 403);
     }
     $sessao = $this->db->doc()->getRepository(get_class($this->SessionEntity))->findOneBy(['uid' => $uid]);
     if (empty($sessao)) {
         throw new \Exception(_("Session not found"), 403);
     }
     if ($tkon->getClaim('sys') != md5($sessao->getBrowser())) {
         throw new \Exception(_("Credentials incorrect"), 403);
     }
     $this->session->set('uid', $uid);
     return ["cod" => base64_decode(Crypt::mycrypt_decrypt(md5(file_get_contents($fprikey)), $tkon->getClaim('cod'))), "id" => $tkon->getClaim('id'), "uid" => $uid];
 }
 /**
  * @inheritdoc
  */
 public function isValid(Token $token)
 {
     $signer = new Sha256();
     $key = new Key($this->pathPublicKey);
     if (!$token->verify($signer, $key)) {
         throw new InvalidDefinitionException('Invalid token');
     }
     $data = new ValidationData();
     $data->setIssuer($token->getClaim('iss'));
     $data->setAudience($token->getClaim('aud'));
     $data->setId($token->getClaim('jti'));
     $isValid = $token->validate($data);
     if (!$isValid) {
         throw new AuthenticationExpiredException('The access token has expired');
     }
     return $isValid;
 }