Ejemplo n.º 1
0
 public function handleRequest(HttpRequest $request)
 {
     $response = new HttpResponse(200, "application/json");
     try {
         if ("POST" !== $request->getRequestMethod()) {
             // method not allowed
             $response->setStatusCode(405);
             $response->setHeader("Allow", "POST");
         } else {
             $response->setHeader('Content-Type', 'application/json');
             $response->setHeader('Cache-Control', 'no-store');
             $response->setHeader('Pragma', 'no-cache');
             $response->setContent(Json::enc($this->_handleToken($request->getPostParameters(), $request->getBasicAuthUser(), $request->getBasicAuthPass())));
         }
     } catch (TokenException $e) {
         if ($e->getResponseCode() === 401) {
             $response->setHeader("WWW-Authenticate", 'Basic realm="OAuth Server"');
         }
         $response->setStatusCode($e->getResponseCode());
         $response->setHeader('Cache-Control', 'no-store');
         $response->setHeader('Pragma', 'no-cache');
         $response->setContent(Json::enc(array("error" => $e->getMessage(), "error_description" => $e->getDescription())));
         if (NULL !== $this->_logger) {
             $this->_logger->logFatal($e->getLogMessage(TRUE) . PHP_EOL . $request . PHP_EOL . $response);
         }
     }
     return $response;
 }
 public function verifyAuthorizationHeader($authorizationHeader)
 {
     if (NULL === $authorizationHeader) {
         throw new ResourceServerException("no_token", "no authorization header in the request");
     }
     // b64token = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="
     $b64TokenRegExp = '(?:[[:alpha:][:digit:]-._~+/]+=*)';
     $result = preg_match('|^Bearer (?P<value>' . $b64TokenRegExp . ')$|', $authorizationHeader, $matches);
     if ($result === FALSE || $result === 0) {
         throw new ResourceServerException("invalid_token", "the access token is malformed");
     }
     $accessToken = $matches['value'];
     $token = $this->_storage->getAccessToken($accessToken);
     if (FALSE === $token) {
         throw new ResourceServerException("invalid_token", "the access token is invalid");
     }
     if (time() > $token['issue_time'] + $token['expires_in']) {
         throw new ResourceServerException("invalid_token", "the access token expired");
     }
     $this->_resourceOwnerId = $token['resource_owner_id'];
     $this->_grantedScope = $token['scope'];
     $resourceOwner = $this->_storage->getResourceOwner($token['resource_owner_id']);
     $this->_resourceOwnerEntitlement = Json::dec($resourceOwner['entitlement']);
     $this->_resourceOwnerExt = Json::dec($resourceOwner['ext']);
 }
Ejemplo n.º 3
0
 public function testAddAuthorizationsUnsupportedScope()
 {
     $h = new HttpRequest("http://www.example.org/api.php");
     $h->setRequestMethod("POST");
     $h->setPathInfo("/authorizations/");
     $h->setHeader("Authorization", "Bearer 12345abc");
     $h->setContent(Json::enc(array("client_id" => "testcodeclient", "scope" => "UNSUPPORTED SCOPE")));
     $response = $this->_api->handleRequest($h);
     $this->assertEquals(400, $response->getStatusCode());
     $this->assertEquals('{"error":"invalid_request","error_description":"invalid scope for this client"}', $response->getContent());
 }
 public function getEntitlement()
 {
     $entitlementFile = $this->config->getSectionValue('SimpleAuthResourceOwner', 'entitlementFile');
     $fileContents = @file_get_contents($entitlementFile);
     if (FALSE === $fileContents) {
         // no entitlement file, so no entitlement
         return array();
     }
     $entitlement = Json::dec($fileContents);
     if (is_array($entitlement) && isset($entitlement[$this->getId()]) && is_array($entitlement[$this->getId()])) {
         return $entitlement[$this->getId()];
     }
     return array();
 }
Ejemplo n.º 5
0
    $request->matchRest("POST", "/hello/:str", function ($str) use(&$response) {
        if ("foo" === $str) {
            // it would make more sense to create something like an ApiException
            // class that would return the code 400 "Bad Request" instead of
            // internal server error as this is a 'mistake' by the client...
            throw new Exception("you cannot say 'foo'!'");
        }
        $response = new HttpResponse(200, "application/json");
        $response->setContent(Json::enc(array("type" => "POST", "response" => "hello " . $str)));
    });
    $request->matchRestDefault(function ($methodMatch, $patternMatch) use($request, &$response) {
        // methodMatch contains all the used request methods 'registrered'
        // through the matchRest method calls above, in this case GET and POST
        //
        // patternMatch indicates (boolean) whether or not the request URL
        // matches any of the patterns 'registered' through the matchRest
        // methods above...
        if (!in_array($request->getRequestMethod(), $methodMatch)) {
            $response = new HttpResponse(405, "application/json");
            $response->setHeader("Allow", implode(",", $methodMatch));
            $response->setContent(Json::enc(array("error" => "method_not_allowed", "error_description" => "request method not allowed")));
        } elseif (!$patternMatch) {
            $response = new HttpResponse(404, "application/json");
            $response->setContent(Json::enc(array("error" => "not_found", "error_description" => "resource not found")));
        }
    });
} catch (Exception $e) {
    $response = new HttpResponse(500, "application/json");
    $response->setContent(Json::enc(array("error" => "internal_server_error", "error_description" => $e->getMessage())));
}
$response->sendResponse();
Ejemplo n.º 6
0
 public function handleRequest(HttpRequest $request)
 {
     $response = new HttpResponse(200, "application/json");
     try {
         if (!$this->_config->getSectionValue("Api", "enableApi")) {
             throw new ApiException("forbidden", "api disabled");
         }
         $this->_rs->verifyAuthorizationHeader($request->getHeader("Authorization"));
         $storage = $this->_storage;
         // FIXME: can this be avoided??
         $rs = $this->_rs;
         // FIXME: can this be avoided??
         $request->matchRest("POST", "/authorizations/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             $data = Json::dec($request->getContent());
             if (NULL === $data || !is_array($data) || !array_key_exists("client_id", $data) || !array_key_exists("scope", $data)) {
                 throw new ApiException("invalid_request", "missing required parameters");
             }
             // client needs to exist
             $clientId = $data['client_id'];
             $client = $storage->getClient($clientId);
             if (FALSE === $client) {
                 throw new ApiException("invalid_request", "client is not registered");
             }
             // scope should be part of "allowed_scope" of client registration
             $clientAllowedScope = new Scope($client['allowed_scope']);
             $requestedScope = new Scope($data['scope']);
             if (!$requestedScope->isSubSetOf($clientAllowedScope)) {
                 throw new ApiException("invalid_request", "invalid scope for this client");
             }
             $refreshToken = array_key_exists("refresh_token", $data) && $data['refresh_token'] ? Utils::randomHex(16) : NULL;
             // check to see if an authorization for this client/resource_owner already exists
             if (FALSE === $storage->getApprovalByResourceOwnerId($clientId, $rs->getResourceOwnerId())) {
                 if (FALSE === $storage->addApproval($clientId, $rs->getResourceOwnerId(), $data['scope'], $refreshToken)) {
                     throw new ApiException("invalid_request", "unable to add authorization");
                 }
             } else {
                 throw new ApiException("invalid_request", "authorization already exists for this client and resource owner");
             }
             $response->setStatusCode(201);
             $response->setContent(Json::enc(array("ok" => true)));
         });
         $request->matchRest("GET", "/authorizations/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             $data = $storage->getApprovalByResourceOwnerId($id, $rs->getResourceOwnerId());
             if (FALSE === $data) {
                 throw new ApiException("not_found", "the resource you are trying to retrieve does not exist");
             }
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("GET", "/authorizations/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             $data = $storage->getApprovalByResourceOwnerId($id, $rs->getResourceOwnerId());
             if (FALSE === $data) {
                 throw new ApiException("not_found", "the resource you are trying to retrieve does not exist");
             }
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("DELETE", "/authorizations/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             if (FALSE === $storage->deleteApproval($id, $rs->getResourceOwnerId())) {
                 throw new ApiException("not_found", "the resource you are trying to delete does not exist");
             }
             $response->setContent(Json::enc(array("ok" => true)));
         });
         $request->matchRest("GET", "/authorizations/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             $data = $storage->getApprovals($rs->getResourceOwnerId());
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("GET", "/applications/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             // $rs->requireEntitlement("urn:x-oauth:entitlement:applications");    // do not require entitlement to list clients...
             $data = $storage->getClients();
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("DELETE", "/applications/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             if (FALSE === $storage->deleteClient($id)) {
                 throw new ApiException("not_found", "the resource you are trying to delete does not exist");
             }
             $response->setContent(Json::enc(array("ok" => true)));
         });
         $request->matchRest("GET", "/applications/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             // FIXME: for now require entitlement as long as password hashing is not
             // implemented...
             $data = $storage->getClient($id);
             if (FALSE === $data) {
                 throw new ApiException("not_found", "the resource you are trying to retrieve does not exist");
             }
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("POST", "/applications/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             try {
                 $client = ClientRegistration::fromArray(Json::dec($request->getContent()));
                 $data = $client->getClientAsArray();
                 // check to see if an application with this id already exists
                 if (FALSE === $storage->getClient($data['id'])) {
                     if (FALSE === $storage->addClient($data)) {
                         throw new ApiException("invalid_request", "unable to add application");
                     }
                 } else {
                     throw new ApiException("invalid_request", "application already exists");
                 }
                 $response->setStatusCode(201);
                 $response->setContent(Json::enc(array("ok" => true)));
             } catch (ClientRegistrationException $e) {
                 throw new ApiException("invalid_request", $e->getMessage());
             }
         });
         $request->matchRest("GET", "/stats/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             $data = $storage->getStats();
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("PUT", "/applications/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             try {
                 $client = ClientRegistration::fromArray(Json::dec($request->getContent()));
                 $data = $client->getClientAsArray();
                 if ($data['id'] !== $id) {
                     throw new ApiException("invalid_request", "resource does not match client id value");
                 }
                 if (FALSE === $storage->updateClient($id, $data)) {
                     throw new ApiException("invalid_request", "unable to update application");
                 }
             } catch (ClientRegistrationException $e) {
                 throw new ApiException("invalid_request", $e->getMessage());
             }
             $response->setContent(Json::enc(array("ok" => true)));
         });
         $request->matchRestDefault(function ($methodMatch, $patternMatch) use($request, $response) {
             if (in_array($request->getRequestMethod(), $methodMatch)) {
                 if (!$patternMatch) {
                     throw new ApiException("not_found", "resource not found");
                 }
             } else {
                 $response->setStatusCode(405);
                 $response->setHeader("Allow", implode(",", $methodMatch));
             }
         });
     } catch (ResourceServerException $e) {
         $response->setStatusCode($e->getResponseCode());
         if ("no_token" === $e->getMessage()) {
             // no authorization header is a special case, the client did not know
             // authentication was required, so tell it now without giving error message
             $hdr = 'Bearer realm="Resource Server"';
         } else {
             $hdr = sprintf('Bearer realm="Resource Server",error="%s",error_description="%s"', $e->getMessage(), $e->getDescription());
         }
         $response->setHeader("WWW-Authenticate", $hdr);
         $response->setContent(Json::enc(array("error" => $e->getMessage(), "error_description" => $e->getDescription())));
         if (NULL !== $this->_logger) {
             $this->_logger->logFatal($e->getLogMessage(TRUE) . PHP_EOL . $request . PHP_EOL . $response);
         }
     } catch (ApiException $e) {
         $response->setStatusCode($e->getResponseCode());
         $response->setContent(Json::enc(array("error" => $e->getMessage(), "error_description" => $e->getDescription())));
         if (NULL !== $this->_logger) {
             $this->_logger->logFatal($e->getLogMessage(TRUE) . PHP_EOL . $request . PHP_EOL . $response);
         }
     }
     return $response;
 }
Ejemplo n.º 7
0
use RestService\Utils\Config;
use RestService\Http\IncomingHttpRequest;
use RestService\Http\HttpRequest;
use OAuth\Token;
use RestService\Utils\Logger;
use RestService\Utils\Json;
$logger = NULL;
$request = NULL;
$response = NULL;
try {
    $config = new Config(dirname(__DIR__) . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . "oauth.ini");
    $logger = new Logger($config->getSectionValue('Log', 'logLevel'), $config->getValue('serviceName'), $config->getSectionValue('Log', 'logFile'), $config->getSectionValue('Log', 'logMail', FALSE));
    $t = new Token($config, $logger);
    $request = HttpRequest::fromIncomingHttpRequest(new IncomingHttpRequest());
    $response = $t->handleRequest($request);
} catch (Exception $e) {
    $response = new HttpResponse(500, "application/json");
    $response->setContent(Json::enc(array("error" => $e->getMessage())));
    if (NULL !== $logger) {
        $logger->logFatal($e->getMessage() . PHP_EOL . $request . PHP_EOL . $response);
    }
}
if (NULL !== $logger) {
    $logger->logDebug($request);
}
if (NULL !== $logger) {
    $logger->logDebug($response);
}
if (NULL !== $response) {
    $response->sendResponse();
}
 /**
  * Implementation of https://tools.ietf.org/html/draft-richer-oauth-introspection
  */
 private function _introspectToken(array $param)
 {
     $r = array();
     $token = Utils::getParameter($param, 'token');
     if (NULL === $token) {
         throw new TokenIntrospectionException("invalid_token", "the token parameter is missing");
     }
     $accessToken = $this->_storage->getAccessToken($token);
     if (FALSE === $accessToken) {
         // token does not exist
         $r['active'] = FALSE;
     } elseif (time() > $accessToken['issue_time'] + $accessToken['expires_in']) {
         // token expired
         $r['active'] = FALSE;
     } else {
         // token exists and did not expire
         $r['active'] = TRUE;
         $r['exp'] = intval($accessToken['issue_time'] + $accessToken['expires_in']);
         $r['iat'] = intval($accessToken['issue_time']);
         $r['scope'] = $accessToken['scope'];
         $r['client_id'] = $accessToken['client_id'];
         $r['sub'] = $accessToken['resource_owner_id'];
         $r['token_type'] = 'bearer';
         // as long as we have no RS registration we cannot set the audience...
         // $response['aud'] = 'foo';
         // add proprietary "x-entitlement"
         $resourceOwner = $this->_storage->getResourceOwner($accessToken['resource_owner_id']);
         if (isset($resourceOwner['entitlement'])) {
             $e = Json::dec($resourceOwner['entitlement']);
             if (0 !== count($e)) {
                 $r['x-entitlement'] = $e;
             }
         }
         // add proprietary "x-ext"
         if (isset($resourceOwner['ext'])) {
             $e = Json::dec($resourceOwner['ext']);
             if (0 !== count($e)) {
                 $r['x-ext'] = $e;
             }
         }
     }
     return $r;
 }
<?php

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php";
use RestService\Utils\Config;
use OAuth\PdoOAuthStorage;
use OAuth\ClientRegistration;
use RestService\Utils\Json;
$config = new Config(dirname(__DIR__) . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . "oauth.ini");
$storage = new PdoOAuthStorage($config);
$storage->initDatabase();
if ($argc !== 2) {
    echo "ERROR: specify manifest file or URL to parse" . PHP_EOL;
    die;
}
$manifestFile = $argv[1];
$fileContents = file_get_contents($manifestFile);
$data = Json::dec($fileContents);
if (NULL === $data || !is_array($data)) {
    echo "ERROR: manifest seems to be in wrong format" . PHP_EOL;
    die;
}
foreach ($data as $d) {
    // go over all app entries
    if (FALSE === $storage->getClient($d['key'])) {
        echo "Adding '" . $d['name'] . "'..." . PHP_EOL;
        $x = array("id" => $d['key'], "name" => $d['name'], "description" => $d['description'], "secret" => NULL, "type" => "user_agent_based_application", "icon" => $d['icons']['128'], "allowed_scope" => implode(" ", $d['permissions']), "redirect_uri" => $d['app']['launch']['web_url']);
        $y = ClientRegistration::fromArray($x);
        $storage->addClient($y->getClientAsArray());
    }
}
<?php

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php";
use RestService\Utils\Config;
use OAuth\PdoOAuthStorage;
use OAuth\ClientRegistration;
use RestService\Utils\Json;
$config = new Config(dirname(__DIR__) . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . "oauth.ini");
$storage = new PdoOAuthStorage($config);
if ($argc !== 2) {
    echo "ERROR: please specify file with client registration information" . PHP_EOL;
    die;
}
$registrationFile = $argv[1];
if (!file_exists($registrationFile) || !is_file($registrationFile) || !is_readable($registrationFile)) {
    echo "ERROR: unable to read client registration file" . PHP_EOL;
    die;
}
$registration = Json::dec(file_get_contents($registrationFile));
foreach ($registration as $r) {
    // first load it in ClientRegistration object to check it...
    $cr = ClientRegistration::fromArray($r);
    if (FALSE === $storage->getClient($cr->getId())) {
        // does not exist yet, install
        echo "Adding '" . $cr->getName() . "'..." . PHP_EOL;
        $storage->addClient($cr->getClientAsArray());
    }
}
Ejemplo n.º 11
0
 public function testValidJson()
 {
     $this->assertFalse(Json::isJson('}'));
     $this->assertTrue(Json::isJson('{}'));
     $this->assertTrue(Json::isJson('null'));
 }
 public function updateResourceOwner(IResourceOwner $resourceOwner)
 {
     $result = $this->getResourceOwner($resourceOwner->getId());
     if (FALSE === $result) {
         $stmt = $this->_pdo->prepare("INSERT INTO resource_owner (id, entitlement, ext) VALUES(:id, :entitlement, :ext)");
         $stmt->bindValue(":id", $resourceOwner->getId(), PDO::PARAM_STR);
         $stmt->bindValue(":entitlement", Json::enc($resourceOwner->getEntitlement()), PDO::PARAM_STR);
         $stmt->bindValue(":ext", Json::enc($resourceOwner->getExt()), PDO::PARAM_STR);
         $stmt->execute();
         return 1 === $stmt->rowCount();
     } else {
         $stmt = $this->_pdo->prepare("UPDATE resource_owner SET entitlement = :entitlement, ext = :ext WHERE id = :id");
         $stmt->bindValue(":id", $resourceOwner->getId(), PDO::PARAM_STR);
         $stmt->bindValue(":entitlement", Json::enc($resourceOwner->getEntitlement()), PDO::PARAM_STR);
         $stmt->bindValue(":ext", Json::enc($resourceOwner->getExt()), PDO::PARAM_STR);
         $stmt->execute();
         return 1 === $stmt->rowCount();
     }
 }