public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { $challenge = function (Response $response, $error = null) { $value = 'Bearer'; if (isset($this->options['realm'])) { $value .= sprintf(' realm="%s"', $this->options['realm']); } if ($error) { $value .= sprintf(' error="%s"', $error); } $response->headers->set('WWW-Authenticate', $value); return $response; }; $authenticate = function ($app, $anonymous) use($request, $type, $catch, $challenge) { $header = $request->headers->get('authorization'); if (!preg_match('/^Bearer (.+)$/i', $header, $matches)) { if ($anonymous) { return (new WwwAuthenticateStackChallenge($app, $challenge))->handle($request, $type, $catch); } return $challenge(new Response('Invalid Authorization header (Format is: "Authorization: Bearer [token]")', 400), 'invalid_request'); } $token = $matches[1]; try { $jws = SimpleJWS::load($token); } catch (\InvalidArgumentException $e) { return $challenge(new Response('Invalid JSON Web Token', 401), 'invalid_token'); } if (!$jws->isValid($this->options['key_provider']($jws->getPayload()))) { return $challenge(new Response('Invalid JSON Web Token', 401), 'invalid_token'); } $request->attributes->set('stack.authn.token', $this->options['token_translator']($jws->getPayload())); return $app->handle($request, $type, $catch); }; return (new Firewall($this->app, ['challenge' => $challenge, 'authenticate' => $authenticate, 'firewall' => $this->options['firewall']]))->handle($request, $type, $catch); }
/** * 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); } }
public function testValidationOfInvalidSimpleJWS() { $date = new DateTime('yesterday'); $this->jws->setPayload(array('exp' => $date->format('U'))); $privateKey = openssl_pkey_get_private(SSL_KEYS_PATH . "private.key", self::SSL_KEY_PASSPHRASE); $this->jws->sign($privateKey); $jws = SimpleJWS::load($this->jws->getTokenString()); $public_key = openssl_pkey_get_public(SSL_KEYS_PATH . "public.key"); $this->assertFalse($jws->isValid($public_key, 'RS256')); }
/** * @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 testValidationOfInvalidSimpleJWSWithExpAsInt() { $date = new DateTime('yesterday'); $data = array('a' => 'b', 'exp' => $date->getTimestamp(), 'iat' => time()); $this->jws->setPayload($data); $privateKey = openssl_pkey_get_private(SSL_KEYS_PATH . 'private.key', self::SSL_KEY_PASSPHRASE); $this->jws->sign($privateKey); $jws = SimpleJWS::load($this->jws->getTokenString()); $public_key = openssl_pkey_get_public(SSL_KEYS_PATH . 'public.key'); $this->assertFalse($jws->isValid($public_key, 'RS256')); }
/** * {@inheritdoc} */ public function decode($token) { try { $jws = SimpleJWS::load($token); } catch (InvalidArgumentException $e) { return false; } if (!$jws->isValid($this->getPublicKey(), self::ALGORYTHM)) { return false; } return $jws->getPayload(); }
public function testGenerateIdentityToken() { $layerIdentityTokenProvider = new \Layer\LayerIdentityTokenProvider(); $privateKey = <<<EOF -----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQDhfR1nIkmSyGUmpTajKgUWpm2f3ObmCgZMTNvadYzwBoJ3ktRG t3cSvRdsyo1EZQPKLOOLv4sXxTE4RrMu/xBnbvUYzn9uvygcW8YT+gW1taJ7GM01 qjKfhAGbC9fhVvJC6VZRmk/ioGBYkA3+7lZTil33szwBK/REcWlPpXOH5wIDAQAB AoGAECEzCT2apbVQBwOqdOF8m7IsBVN38Nymtq6Iy4e9HS5aBtOp+6UED4MXOeED WfEf5EZxwH1jJcAlVTE5gBMeyST0dZ1BYrHU/RKtPAb/RqoxIy2ON9lQOzV+xR/Z 0W8LcrAHbIgu7iBGecTSsTrNw0i5Wo4684gEMM3MDtkbIQECQQD2W00r9CA+A8uL xXa/p/8YLw3He4tAeU13qb7W/Wx0RfF5oZT3aqUwvgLTDP+ASycFUAD1MjKYOQpP mwDu70eZAkEA6lCzE77b3xWFsNv9GysqTYQr3CoNmxWwGOdxsBsKrmuRdwRu5YvG p00JG48VaNs5RXTiO42kefjHkPCQ1Wz7fwJBAOJNWISpyvxsrAwHJmBESHbEspmu iWp+g4UK7v266mec4IdkwNzOoFQ4F4wcApCteHjO1zJmHEftDeW2c5MJRvECQHOO wxJs4UC++4UCqWv5uM4r7fmRn84pPwS5N/9TBsyIbmAVBqAcdCdUPbaitTtWSoNv ppcaPtCMmddoXPV03v8CQE01dePAfsVIACSSHTFSx9nmLzRmMqFT04uaBKDcqgEw Ks3Omb1JuXYxR4elMX4d5Y3JPUMbqUPKylnE4X9ogbc= -----END RSA PRIVATE KEY----- EOF; $layerIdentityTokenProvider->setPrivateKey($privateKey); $layerIdentityTokenProvider->setKeyID('foo'); $layerIdentityTokenProvider->setProviderID('bar'); $identityToken = $layerIdentityTokenProvider->generateIdentityToken('sean', 'nonce'); $publicKey = <<<EOF -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhfR1nIkmSyGUmpTajKgUWpm2f 3ObmCgZMTNvadYzwBoJ3ktRGt3cSvRdsyo1EZQPKLOOLv4sXxTE4RrMu/xBnbvUY zn9uvygcW8YT+gW1taJ7GM01qjKfhAGbC9fhVvJC6VZRmk/ioGBYkA3+7lZTil33 szwBK/REcWlPpXOH5wIDAQAB -----END PUBLIC KEY----- EOF; $expectedISSResult = 'bar'; $expectedPRNResult = 'sean'; $public_key = openssl_pkey_get_public($publicKey); $jws = SimpleJWS::load($identityToken); if ($jws->isValid($public_key, 'RS256')) { $payload = $jws->getPayload(); $this->assertEquals($expectedISSResult, $payload['iss'], 'iss did not match expected value'); $this->assertEquals($expectedPRNResult, $payload['prn'], 'prn did not match expected value'); } else { $this->assertFalse($jws->isValid($public_key, 'RS256'), 'SimpleJWS did not create a valid identity token'); } }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { if (false === $request->hasHeader('Authorization')) { if (false === $this->allRequests) { return $next($request, $response); } return $this->invalidResponse; } $token = $request->getHeaderLine('Authorization'); if (false === strpos($token, 'Bearer ')) { return $this->invalidResponse; } $token = substr($token, 7); /** @var SimpleJWS $jws */ $jws = SimpleJWS::load($token, false); if (false === $jws->isValid($this->publicKey, $this->encoder)) { return $this->invalidResponse; } return $next($request->withAttribute('jwt', $jws->getPayload()), $response); }
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); }
/** * {@inheritdoc} */ function verifyToken(App $app, $token) { try { // Load token $jws = SimpleJWS::load($token); $publicKey = openssl_pkey_get_public('file://' . $app->getAppDir() . '/public.key'); // verify that the token is valid and had the same values // you emitted before while setting it as a cookie if ($jws->isValid($publicKey, 'RS256')) { $payload = $jws->getPayload(); $response = new JsonResponse(array('authorized' => true)); } else { $response = new JsonResponse(array('authorized' => false), 401); } } catch (\InvalidArgumentException $ex) { return new JsonResponse(array('error' => 'Invalid token'), 400); } return new $response(); }
/** * Create Appellate Reviews for an Issue * * @return mixed */ public function newReview() { $body = $this->requestBody; $headers = apache_request_headers(); $arr = explode(" ", $headers['Authorization']); $value = $arr[1]; $jws = SimpleJWS::load($value, true); $user_arr = $jws->getPayLoad(); $user = $user_arr['uid']; error_log("Creating Review for user with iD: " . $user); $shared = $this->getDi()->getShared('db'); $con = $shared->query("INSERT INTO appellate_reviews(legalhead, subjectmatter, issue, title, content, user_id) VALUES (?,?,?,?,?,?)", array($body->legalHead, $body->subjectMatter, $body->issue, $body->title, $body->content, $user)); $con->execute(); $id = $shared->lastInsertId(); $data = $shared->query("SELECT appellate_reviews.id, legalhead, subjectmatter, issue, title, content, name FROM appellate_reviews join users on users.id = user_id WHERE appellate_reviews.id = {$id}")->fetch(); return $data; }
} // Basic auth, for programmatic responses $headers = apache_request_headers(); if (isset($headers['X_API_KEY'])) { $user = new \PhalconRest\Controllers\UserController(); if (!$user->loginWithPrivateKey($headers['X_API_KEY'])) { throw new \PhalconRest\Exceptions\HTTPException("Invalid/Expired API Key", 403); } else { return true; } } if (isset($headers['Authorization']) && !empty($headers['Authorization'])) { $arr = explode(" ", $headers['Authorization']); if (count($arr) > 1) { $value = $arr[1]; $jws = SimpleJWS::load($value, true); return true; // if (!$jws->isExpired()) { // return true; // } else // throw new \PhalconRest\Exceptions\HTTPException("Invalid/Expired Token Key", 403); } else { throw new \PhalconRest\Exceptions\HTTPException("No Key Set", 403); } } // If we made it this far, we have no valid auth method, throw a 401. throw new \PhalconRest\Exceptions\HTTPException('Must login or provide credentials.', 401, array('dev' => 'Please provide credentials by either passing in a session token via cookie, or providing password and username via BASIC authentication.', 'internalCode' => 'Unauth:1')); }); /** * Mount all of the collections, which makes the routes active. */
protected function expiredToken() { $jws = new SimpleJWS(['alg' => 'HS256']); $jws->setPayload(['exp' => (new \DateTime('yesterday'))->format('U')] + $this->payload()); $jws->sign('s3cr3t'); return $jws->getTokenString(); }
/** * Proxy JWS::load static method to allow unit testing. * Creates an instance of a JWS from a JWT. * * @param string $jwsTokenString * @return JWS * @throws \InvalidArgumentException */ public function callLoad($jwsTokenString, $allowUnsecure = false, Encoder $encoder = null, $encryptionEngine = 'OpenSSL') { return parent::load($jwsTokenString, $allowUnsecure, $encoder, $encryptionEngine); // TODO: Change the autogenerated stub }