/** * 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']); }
/** * 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); } }
/** * 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; }
/** * @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)); }
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'); }
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; }
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; }
/** * @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']; }); }
/** * 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; }
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; }
/** * 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; }
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]]; }
$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); return $response; } }
/** * @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; }