searching for a good authentication method for my rest api i came a cross this :
"What is stateless authentication?
Again, stateless means without state. But, how can we identify a user from a token without having any state on the server? Surprisingly, it’s very easy! just send all the data to the client.
So what would you store/send (send to client/network)? The most trivial example is an access token. Access tokens usually have a unique ID, an expiration date and the ID of the client that created it. To store this, you would just put this data into a JSON object, and encode it using base64."
Now, having a self-contained token, you will need to make sure that nobody can manipulate the data. For this you should sign it using MAC algorithm or any other digital signature method available.
This is a little confusing for me , how can i validate the access token when the request comes(nothing stored to match it), but i find it a good idea and i want to implement it, any advice will be very helpful.
My rest api is very simple I receive every request to index.php , then i create new object with the request class to analyze every element of the request.
request class looks like this :
<?php
class Request {
public $url_elements;
public $verb;
public $parameters;
public function __construct() {
$this->verb = $_SERVER['REQUEST_METHOD'];
$this->url_elements = explode('/', $_SERVER['PATH_INFO']);
$this->parseIncomingParams();
$this->format = 'json';
if(isset($this->parameters['format'])) {
$this->format = $this->parameters['format'];
}
return true;
}
public function parseIncomingParams() {
$parameters = array();
if (isset($_SERVER['QUERY_STRING'])) {
parse_str($_SERVER['QUERY_STRING'], $parameters);
}
$body = file_get_contents("php://input");
$content_type = false;
if(isset($_SERVER['CONTENT_TYPE'])) {
$content_type = $_SERVER['CONTENT_TYPE'];
}
switch($content_type) {
case "application/json":
$body_params = json_decode($body);
if($body_params) {
foreach($body_params as $param_name => $param_value) {
$parameters[$param_name] = $param_value;
}
}
$this->format = "json";
break;
case "application/x-www-form-urlencoded":
parse_str($body, $postvars);
foreach($postvars as $field => $value) {
$parameters[$field] = $value;
}
$this->format = "html";
break;
default:
break;
}
$this->parameters = $parameters;
}
}
?>
After this i proceed with the proper controller that is the first element after index.php/
Thank you very much for your time and sorry if the question is not very clear as i am new to rest :/
Related
I am trying to use the Sinch Rest API with PHP to mute and unmute specific participants from Conference calls but have not been able to find an example of how to send an application signed request with PHP. I have been trying to work off of this documentation from Sinch here https://www.sinch.com/docs/voice/rest/index.html#muteunmuteconfparticipant
My initial guesses are that this would require the use of CURL and that I would also need to use similar pieces of this example to sign my application but I"m not sure how to combine the two. https://github.com/sinch/php-auth-ticket
Any help appreciated. Thanks!
edit: #cjensen I added this code snippet I've been working on to try and use as the signed request maker. It's very similar to that github link above
<?php
class SinchTicketGenerator
{
private $applicationKey;
private $applicationSecret;
public function __construct($applicationKey, $applicationSecret)
{
$this->applicationKey = $applicationKey;
$this->applicationSecret = $applicationSecret;
}
public function generateTicket()
{
$request = [
'command' => 'mute',
];
$requestJson = preg_replace('/\s+/', '', json_encode($request));
$requestBase64 = $this->base64Encode($requestJson);
$digest = $this->createDigest($requestJson);
$signature = $this->base64Encode($digest);
$requestSigned = $requestBase64.':'.$signature;
return $requestSigned;
}
private function base64Encode($data)
{
return trim(base64_encode($data));
}
private function createDigest($data)
{
return trim(hash_hmac('sha256', $data, base64_decode($this->applicationSecret), true));
}
}
$generator = new SinchTicketGenerator('app-key', 'app-secret');
$signedrequest = $generator->generateTicket();
echo $signedrequest;
?>
So long story short i was stuck with this old PHP utility that is using an old zend framework. I am having trouble when it times-out it doesnt retry so it fails. i have done everything from changing timeout timers to changing max redirects and everything else i can do with the settings and still get the same thing.
I get a consistent
Fatal error: Uncaught exception 'Zend_Http_Client_Exception' with message 'Unable to read response, or response is empty'
and if i happen to try it enough it will work without issue. its just getting to retry it is the problem.
Im not sure where to think to put the retry logic.
I've seen some say it would go somewhere here (Zend_http_client)
public function request($method = null)
{
if (! $this->uri instanceof Zend_Uri_Http) {
/** #see Zend_Http_Client_Exception */
require_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
}
if ($method) {
$this->setMethod($method);
}
$this->redirectCounter = 0;
$response = null;
// Make sure the adapter is loaded
if ($this->adapter == null) {
$this->setAdapter($this->config['adapter']);
}
// Send the first request. If redirected, continue.
do {
// Clone the URI and add the additional GET parameters to it
$uri = clone $this->uri;
if (! empty($this->paramsGet)) {
$query = $uri->getQuery();
if (! empty($query)) {
$query .= '&';
}
$query .= http_build_query($this->paramsGet, null, '&');
$uri->setQuery($query);
}
$body = $this->_prepareBody();
$headers = $this->_prepareHeaders();
// Open the connection, send the request and read the response
$this->adapter->connect($uri->getHost(), $uri->getPort(),
($uri->getScheme() == 'https' ? true : false));
$this->last_request = $this->adapter->write($this->method,
$uri, $this->config['httpversion'], $headers, $body);
$response = $this->adapter->read();
if (! $response) {
/** #see Zend_Http_Client_Exception */
require_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
}
$response = Zend_Http_Response::fromString($response);
if ($this->config['storeresponse']) {
$this->last_response = $response;
}
I was thinking it could also go here (in my own code)
$eventResponse = new Response($Client->Event(
$theEvent,null));
if (!$throwEventResponse->getResponseStatusOk()) {
$ex = new ResponseException("Unable to complete event.");
$ex->setErrorList($throwEventResponse->getErrorList());
throw $ex;
}
Im at a bit of a loss and im not sure how to go about it to best work for what i need.
Thanks in advance!
Found that by changing the type of HTTP request from HTML 1.1 to 1.0 fixed the issue i was having with the calls moving to the next without waiting for the previous call to finish.
pushing the second request before the other was done caused a weird caching issue and the request failed.
I have below code that save the country information in Database. Below code works fine. There is no problem in that.
private function SaveChanges(\App\Http\Requests\CountryRequest $request) {
if($request['CountryID'] == 0) {
$Country = new \App\Models\CountryModel();
}
else {
$Country = $this->GetCountry($request['CountryID']);
}
$Country->Country = $request['Country'];
$Country->CountryCode = $request['CountryCode'];
$Country->save();
return redirect()->route($this->AllCountries);
}
Now, I decided to shift the working of above method inside a new class like below. Here I am reading the JSON data
class CountryData {
public function CreateCountry($CountryObject) {
$obj = json_decode($CountryObject);
$Country = new \App\Models\CountryModel();
$Country->Country = $CountryObject->Country;
$Country->CountryCode = $CountryObject->CountryCode;
$Country->save();
return true;
}
}
and the original function is changed like below. Sending the Request parameter in the form of JSON.
private function SaveChanges(\App\Http\Requests\CountryRequest $request) {
$data = array(
'Country' => $request['Country'],
'CountryCode' => $request['CountryCode'],
'CountryID' => $request['CountryID']
);
if($request['CountryID'] == 0) {
$result = (new \CountryData())->CreateCountry( json_encode($data) );
}
return redirect()->route($this->AllCountries);
}
Question: Is my approach correct to send converted request object to JSON object and reading in an another Class .
I am doing that so that I can create a new controller and call the CreateCountry from class CountryData to return JSON data for an Android App.
Well, I don't think it's a good approach. Your CountryData class acts as a service, so I think it hasn't have to know anything about JSON, that is part of the interface between your business logic and the external side of your system (Android app, web interface, etc.)
Your new Controller may receive JSON objects and answer with JSON objects, but it must convert the JSON received to your business classes, then pass them to your services, in this case CountryData (not a good name, though).
So the logic should be:
Controller:
- receive request data
- call service and save or whatever
- encode to JSON
- send the response in JSON format
So your business classes don't know anything about JSON.
A not fully code solution is provided as an idea, but it lacks error management, and more work to do. It's based on some Laravel 5 features. Also I don't know if you're using REST or what kind of request are you doing...
use App\Http\Controllers\Controller;
class CountryController() extends Controller {
public function store(\App\Http\Requests\CountryRequest $request) {
// TODO manage errors
$countryModel = $this->createOrUpdateCountry($request);
// Laravel way to response as JSON
return redirect()->json($this->country2Array($countryModel);
}
private function createOrUpdateCountry(\App\Http\Requests\CountryRequest $request) {
$countryId = $request['CountryID'];
if($id == 0) {
$countryModel = new \App\Models\CountryModel();
} else {
$countryModel = $this->GetCountry($countryId);
}
$countryModel->Country = $request['Country'];
$countryModel->CountryCode = $request['CountryCode'];
// You must have an initialised instance of CountryDAO
// TODO manage errors
$countryDAO->saveOrUpdate($countryModel);
return $countryModel;
}
private function country2Array($countryModel) {
$data = array(
'country' => $countryModel->Country,
'countryCode' => $countryModel->CountryCode,
'countryId' => $countryModel->CountryID
);
return $data;
}
}
/**
* Formerly CountryData
*/
class CountryDAO {
public function saveOrUpdate($countryModel) {
// TODO Manage errors or DB exceptions
// I'd put the DB save access/responsability here instead of in CountryModel
$countryModel->save();
return true;
}
}
First of you should not do any conversions to objects and so on.
Second, since the request object should be an array as shown on your example I suggest you to use the "fill" method of Laravel, instead of looping on hand all of the request elements.
Your code for saving the request should be as follows:
class CountryData {
public function CreateCountry($requestData) {
$Country = new \App\Models\CountryModel();
$country->fill($requestData);
$Country->save();
return true;
}
}
The "fill" method loops all of the array keys and tries to set them into the object instance if it has those keys as properties. If there are any extra fields, they are trimmed and you wont get any errors.
Cheers! :)
I am trying to setup an Oauth server using the pecl-php oauth library http://php.net/manual/en/book.oauth.php
This code assumes that the client has already received a user verified access token, for simplicity sake I've not included any database calls and have hardcoded matching values into my client and provider.
Class OauthVerify
{
private static $consumer_secret = 'f63ed7f7a8899e59d3848085c9668a0d';
private static $token_secret = '72814e6059441037152eecef2e8559a748b84259';
private $provider;
public function __construct()
{
$this->provider = new OAuthProvider();
$this->provider->consumerHandler(array($this,'consumerHandler'));
$this->provider->timestampNonceHandler(array($this,'timestampNonceHandler'));
$this->provider->tokenHandler(array($this,'checkAccessToken'));
}
//Check the client request
public function checkRequest()
{
try {
$this->provider->checkOAuthRequest();
} catch (Exception $Exception) {
return OAuthProvider::reportProblem($Exception);
}
return true;
}
public static function timestampNonceHandler($Provider)
{
//I'm leaving out this logic now, to keep it simple and for testing purposes
return OAUTH_OK;
}
public static function consumerHandler($Provider)
{
//I'm leaving out this logic now, to keep it simple and for testing purposes
$Provider->consumer_secret = self::$consumer_secret;
return OAUTH_OK;
}
public static function checkAccessToken($Provider)
{
$Provider->token_secret = self::$token_secret;
return OAUTH_OK;
}
}
The above code should give me the barebones I need to authenticate an Oauth request.
Before any particular route is executed I call the $OauthVerify->checkRequest() method which checks if the client request is valid, however the server keeps throwing a 'signatures do not match' error. I don't think that the problem is with the clients as I've tried both postman (for chrome) and a PHP implementation and they both generate the same signature. I have however for interest sake included my client call.
$consumer_key = '87d6d61e87f0e30d8747810ae40041d1';
$consumer_secret = 'f63ed7f7a8899e59d3848085c9668a0d';
$token= 'b9d55b3ec4b755d3fe25d7a781da1dfd044b5155';
$token_secret = '72814e6059441037152eecef2e8559a748b84259';
$timestamp = '1417515075';
$nonce = '9QV4rn';
$version = '1.0';
$method = 'GET';
$url = 'https://localhost/micro/v1/nappi';
try {
$oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
$oauth->disableSSLChecks();
$oauth->setNonce($nonce);
$oauth->setTimestamp($timestamp);
$oauth->setToken($token, $token_secret);
$oauth->setVersion($version);
$oauth->fetch("$url");
$json = json_decode($oauth->getLastResponse());
print_r($json);
}
catch(OAuthException $E) {
print_r($E);
}
I've burned a good couple of hours trying to figure this out, someone please help!
I finally managed to solve it, my .htaccess file had a rewrite rule that was processing a _url parameter for my framework. This parameter was ofcourse being included in the signature that the server generated. I simply instructed OAuth Provider to ignore the the _url parameter in my constructor:
$this->provider->setParam('_url',NULL);,
that was all it took, everything runs perfectly now.
I'm experimenting with php mvc and I'm stucked with the following issue. My request and router classes are really simple and I would like to extend theme to can handle controller calls from sub folders and to controller classes functions should be able to pick up url variables send it threw get and post.
my router looks as it follows
class Router{
public static function route(Request $request){
$controller = $request->getController().'Controller';
$method = $request->getMethod();
$args = $request->getArgs();
$controllerFile = __SITE_PATH.'/controllers/'.$controller.'.php';
if(is_readable($controllerFile)){
require_once $controllerFile;
$controller = new $controller;
if(!empty($args)){
call_user_func_array(array($controller,$method),$args);
}else{
call_user_func(array($controller,$method));
}
return;
}
throw new Exception('404 - '.$request->getController().'--Controller not found');
}
}
and Request class
private $_controller;
private $_method;
private $_args;
public function __construct(){
$parts = explode('/',$_SERVER['REQUEST_URI']);
$this->_controller = ($c = array_shift($parts))? $c: 'index';
$this->_method = ($c = array_shift($parts))? $c: 'index';
$this->_args = (isset($parts[0])) ? $parts : array();
}
public function getController(){
return $this->_controller;
}
public function getMethod(){
return $this->_method;
}
public function getArgs(){
return $this->_args;
}
}
The problem is:when I try to send threw ajax, variables to a controller method this are not recognized because of its url structure.
For example
index/ajax?mod_title=shop+marks&domain=example
is accepted just if it look
index/ajax/shop+mark/example
Your code contains what is known as an LFI vulnerability and is dangerous in its current state.
You should whitelist your what can be used as your $controller, as otherwise an attacker could try to specify something using NUL bytes and possibly going up a directory to include files that SHOULD NOT be ever included, such as /etc/passwd, a config file, whatever.
Your router is not safe for use; beware!
edit: example on whitelisting
$safe = array(
'ajax',
'somecontroller',
'foo',
'bar',
);
if(!in_array($this->_controller, $safe))
{
throw new Exception(); // replace me with your own error 404 stuff
}
Since your Request class uses a URI segments approach for identifying controller, action and arguments, global variables such as $_GET or $_REQUEST are not taken into account from within your Request.
What you need to do is to make some additions to your Request code. Specifically:
Remove the line:
$this->_args = (isset($parts[0])) ? $parts : array();
And add the following:
$all_parts = (isset($parts[0])) ? $parts : array();
$all_parts['get'] = $_GET;
$this->_args = $all_parts;
This way, $_GET (ie variables passed via the url) variables will be available in the actions called, as they will be in $args (they will be available as $args['get'] actually, which is the array that holds the $_GET vars, so you will be able to have access to domain=example by using $args['get']['domain']).
Ofcourse, you can add one more method in your Request class (e.g. query) that might look like that:
public function query($var = null)
{
if ($var === null)
{
return $_GET;
}
if ( ! isset($_GET[$var]) )
{
return FALSE;
}
return $_GET[$var];
}
This way, you can get a single variable from the url (e.g. $request->query('domain')) or the whole $_GET array ($request->query()).
That's because php will put "?mod_title=..." in the $_GET array automatically. Your getArgs() function should check for $_GET, $_POST or $_REQUEST.
If you're trying for a minimal MVC approach, have a look at rasmus' example: http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html
If your use case is going to get more complex, have a look at how Zend (http://framework.zend.com/manual/en/zend.controller.html) or Symfony (https://github.com/symfony/symfony/tree/master/src/Symfony/Component/Routing) do their stuff.
Choose any popular MVC to see how they implement it under the hood. In addition, spl_autoload_register and namespace are your friends.