/** * {@inheritdoc} */ public function encode(array $data) { $jws = new SimpleJWS(array('alg' => self::ALGORYTHM)); $jws->setPayload($data); $jws->sign($this->getPrivateKey()); return $jws->getTokenString(); }
/** * {@inheritdoc} */ protected function authorizeUser(App $app, $email, $password) { if (isset($app['db'])) { $db = $app['db']; } else { if (isset($app['orm.em'])) { $db = $app['orm.em']->getConnection(); } else { throw new Exception("DB connection not found"); } } // User array $userArray = Users::getInstance($db)->getByEmail($email); // User for encode password $user = new User($email, $password, array('ROLE_USER'), true, true, true, true); // Encoded password $encodedPasswd = $app['security.encoder.digest']->encodePassword($password, $user->getSalt()); if ($userArray['password'] !== $encodedPasswd) { $token = false; } else { // Datetime tomorrow $date = new \DateTime('tomorrow'); // Json Web Token $jws = new SimpleJWS(array('alg' => 'RS256')); $jws->setPayload(array('uid' => $userArray['id'], 'exp' => $date->format('U'))); $privateKey = openssl_pkey_get_private('file://' . $app->getAppDir() . '/private.key', '123456789'); $jws->sign($privateKey); $token = $jws->getTokenString(); } return $token; }
/** * Exchange Username and Password for JWToken * * @throws HTTPException * @return array */ public function login_jwt() { $username = $this->requestBody->username; $pwd = $this->requestBody->password; /** @var User $user */ $user = User::findFirstByUsername($username); if ($user && $user->getPassword() == md5($pwd)) { $user->setExpires(date("Y-m-d H:i:s", strtotime("+5 minutes"))); $user->setPrivateKey(md5(time() . $user->getName() . "lp")); $user->save(); // TODO: Generate JWT Here $jws = new SimpleJWS(array('alg' => 'RS256')); $jws->setPayload(array('uid' => $user->getId(), "name" => $user->getName())); return array("token" => $jws->getTokenString(), "expires" => $user->getExpires()); } else { throw new HTTPException("Invalid Username/Password", 401); } }
/** * @Phprest\Route(method="POST", path="/tokens") * * @param Request $request * * @return Response\Created * * @throws Exception\UnprocessableEntity * @throws Exception\Unauthorized */ public function post(Request $request) { try { /** @var Entity\Credential $credentials */ $credentials = $this->deserialize('Api\\Token\\Entity\\Credential', $request); } catch (RuntimeException $e) { throw new Exception\UnprocessableEntity(0, [new Service\Validator\Entity\Error('', $e->getMessage())]); } if (count($errors = $this->getErrors($credentials))) { throw new Exception\UnprocessableEntity(0, $this->getFormattedErrors($errors)); } if ($credentials->email === '*****@*****.**' && $credentials->password === 'info') { $jws = new SimpleJWS(['alg' => 'HS256']); $jws->setPayload(['uid' => 1, 'iat' => 1448201407]); $jws->sign('secret-key'); return new Response\Ok(['token' => $jws->getTokenString()]); } throw new Exception\Unauthorized(); }
public function generateIdentityToken($user_id, $nonce) { $this->_checkLayerConfig(); $jws = new SimpleJWS(array('typ' => 'JWT', 'alg' => 'RS256', 'cty' => 'layer-eit;v=1', 'kid' => $this->_keyID)); $jws->setPayload(array('iss' => $this->_providerID, 'prn' => $user_id, 'iat' => round(microtime(true) * 1000), 'exp' => round(microtime(true) * 1000) + 120, 'nce' => $nonce)); $privateKey = openssl_pkey_get_private($this->_privateKey); $jws->sign($privateKey); $identityToken = $jws->getTokenString(); return $identityToken; }
private function doPost(string $resource, array $payload) : Generator { $privateKey = openssl_pkey_get_private($this->keyPair->getPrivate()); $details = openssl_pkey_get_details($privateKey); if ($details["type"] !== OPENSSL_KEYTYPE_RSA) { throw new \RuntimeException("Only RSA keys are supported right now."); } $uri = (yield $this->getResourceUri($resource)); $enc = new Base64UrlSafeEncoder(); $jws = new SimpleJWS(["alg" => "RS256", "jwk" => ["kty" => "RSA", "n" => $enc->encode($details["rsa"]["n"]), "e" => $enc->encode($details["rsa"]["e"])], "nonce" => (yield $this->getNonce($uri))]); $payload["resource"] = $payload["resource"] ?? $resource; $jws->setPayload($payload); $jws->sign($privateKey); $request = (new Request())->setMethod("POST")->setUri($uri)->setBody($jws->getTokenString()); $response = (yield $this->http->request($request)); $this->saveNonce($response); return $response; }
private function doPost($resource, array $payload) { if (!is_string($resource)) { throw new InvalidArgumentException(sprintf("\$resource must be of type string, %s given.", gettype($resource))); } $privateKey = openssl_pkey_get_private($this->keyPair->getPrivate()); $details = openssl_pkey_get_details($privateKey); if ($details["type"] !== OPENSSL_KEYTYPE_RSA) { throw new \RuntimeException("Only RSA keys are supported right now."); } $uri = (yield $this->getResourceUri($resource)); $atempt = 0; do { $attempt++; if ($attempt > 3) { throw new AcmeException("POST request to {$uri} failed, received too many badNonce errors."); } $enc = new Base64UrlSafeEncoder(); $jws = new SimpleJWS(["alg" => "RS256", "jwk" => ["kty" => "RSA", "n" => $enc->encode($details["rsa"]["n"]), "e" => $enc->encode($details["rsa"]["e"])], "nonce" => (yield $this->getNonce($uri))]); $payload["resource"] = isset($payload["resource"]) ? $payload["resource"] : $resource; $jws->setPayload($payload); $jws->sign($privateKey); $request = (new Request())->setMethod("POST")->setUri($uri)->setBody($jws->getTokenString()); try { $response = (yield $this->http->request($request)); $this->saveNonce($response); if ($response->getStatus() === 400) { $info = json_decode($response->getBody()); if ($info && isset($info->type) && $info->type === "urn:acme:badNonce") { continue; } } } catch (Exception $e) { throw new AcmeException("POST request to {$uri} failed.", null, $e); } catch (Throwable $e) { throw new AcmeException("POST request to {$uri} failed.", null, $e); } (yield new CoroutineResult($response)); return; } while (true); }
protected function expiredToken() { $jws = new SimpleJWS(['alg' => 'HS256']); $jws->setPayload(['exp' => (new \DateTime('yesterday'))->format('U')] + $this->payload()); $jws->sign('s3cr3t'); return $jws->getTokenString(); }