/** * Converts and signs a PHP object or array into a JWT string. * * @param object|array $payload PHP object or array * @param string $key The secret key. * If the algorithm used is asymmetric, this is the private key * @param string $alg The signing algorithm. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256' * @param array $head An array with header elements to attach * * @return string A signed JWT * * @uses jsonEncode * @uses urlsafeB64Encode */ public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) { $header = array('typ' => 'JWT', 'alg' => $alg); if ($keyId !== null) { $header['kid'] = $keyId; } if (isset($head) && is_array($head)) { $header = array_merge($head, $header); } $segments = array(); $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header)); $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload)); $signing_input = implode('.', $segments); $signature = JWT::sign($signing_input, $key, $alg); $segments[] = JWT::urlsafeB64Encode($signature); return implode('.', $segments); }
if (!isset($server['PHP_AUTH_USER'], $server['PHP_AUTH_PW'])) { return $this->api->json($res, ['error' => 'BadArguments', 'message' => 'You need to give a username and a password'], 400); } $username = $server['PHP_AUTH_USER']; $password = $server['PHP_AUTH_PW']; if (!($user = $users->read($username))) { return $this->api->json($res, ['error' => 'BadCredentials', 'message' => 'User or password not ok'], 403); } if (!$user->login($password)) { return $this->api->json($res, ['error' => 'BadCredentials', 'message' => 'User or password not ok'], 403); } $now = new DateTime(); $future = new DateTime('now +2 hours'); $server = $req->getServerParams(); try { $payload = ['iat' => $now->getTimeStamp(), 'exp' => $future->getTimeStamp(), 'jti' => JWT::urlsafeB64Encode(random_bytes(32)), 'sub' => $username, 'scope' => $user->getRoles()]; } catch (Exception $e) { die('Could not generate a random string. Is our OS secure?'); } $secret = $app['config']->get('secretToken'); $token = JWT::encode($payload, $secret, 'HS256'); $data['status'] = 'ok'; $data['token'] = $token; return $res->withStatus(201)->withHeader('Content-Type', 'application/json')->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); }); $this->get('/credentials', function ($req, $res) { if (!isset($this->token)) { return $res->withStatus(401)->withJson([]); } $res->withJson($this->token->scope); });