Php php throw error not allowed
I want to auth the user using firebase and identity api before give the user the ability to make requests to my api endopints. I always get this error when I try to pass the token I get from : The problem is that I’m using the get method on client side.
Uncaught Slim\Exception\HttpMethodNotAllowedException: Method not allowed. Must be one of: GET
I’m trying to implement firebase auth in my chrome extension and in my slim php REST API . After some configuration with the extension manifest and with the php server code I have a problem with the token verification. I always get this error when I try to pass the token I get from chrome.identity.getAuthToken() :
PHP Fatal error: Uncaught Slim\Exception\HttpMethodNotAllowedException: Method not allowed. Must be one of: GET
The problem is that I’m using the get method on client side. My axios code is this:
axios.get('http://localhost:3000/keygen', < headers: < 'Authorization': `Bearer $` > >) .then( (response) => < console.log(response, response.data); this.password = response.data.generated_password; this.createdPassword = response.data.generated_password; >);
and on the server side I have this code:
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; require_once __DIR__.'/vendor/autoload.php'; //I'm adding headers because I'm on localhost and I have a CORS error if I don't specify the chrome ectension id from witch the requests come from. This problem will not occur on live server header("Access-Control-Allow-Origin: chrome-extension://oegddbimpfdpbojkmfibkebnagidflfc"); header("Access-Control-Allow-Methods: GET, POST"); header("Access-Control-Allow-Headers: Authorization"); header("Access-Control-Allow-Credentials: true"); require_once __DIR__.'/vendor/autoload.php'; $app = AppFactory::create(); $rawPublicKeys = file_get_contents('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'); $keys = json_decode($rawPublicKeys, true); $app->add(new Tuupola\Middleware\JwtAuthentication([ //"ignore" => [""] "secret" => $keys, "header" => "X-Authorization", "regexp" => "/Bearer\s+(.*)$/i", "algorithm" => ["RS256"], ])); $app->get('/keygen', function(Request $request, Response $response, $args)< $password = bin2hex(random_bytes(3)); $response->getBody()->write( json_encode(['generated_password' => $password]) ); return $response->withHeader('Content-Type','application/json'); >);
How I can fix this? I want to auth the user using firebase and identity api before give the user the ability to make requests to my api endopints. Thanks for the help.
I’ve modified the php code following the slim provided documentation and now this issue seems solved but I get 401 error. I will post another question for this issue
$app->options('/', function ($request, $response, $args) < return $response; >); $app->add(function ($request, $handler) < $response = $handler->handle($request); return $response ->withHeader('Access-Control-Allow-Origin', 'chrome-extension://oegddbimpfdpbojkmfibkebnagidflfc') ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization') ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS'); >); $rawPublicKeys = file_get_contents('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'); $keys = json_decode($rawPublicKeys, true); $app->add(new Tuupola\Middleware\JwtAuthentication([ //"ignore" => [""] "secret" => $keys, "header" => "X-Authorization", "regexp" => "/Bearer\s+(.*)$/i", "algorithm" => ["RS256"], ])); $app->get('/keygen', function(Request $request, Response $response, $args)< $password = bin2hex(random_bytes(3)); $response->getBody()->write( json_encode(['generated_password' => $password]) ); return $response->withHeader('Content-Type','application/json'); >); $app->map(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], '/', function ($request, $response) < throw new HttpNotFoundException($request); >);
It must be the assigned route for any request has been assigned as GET, but you may be going with other method rather than GET, please check once if there is any time of mismatch in the Route.
For alternate solution you can also mention the Route as any , as:
Route::any('/', 'PagesController@index');
The problem was caused by OPTIONS request that is made from localhost during development. Since I didn’t configured any endpoint to accept OPTIONS requests, I’ve solved the issue with a middleware that is managing CORS.
PHP exec throw exception not working, You cannot throw an exception in ones script that you’ve exec’d in another. Also, since you’re not catching the exception in test.php, the following applies: If an exception is not caught, a PHP Fatal Error will be issued with an «Uncaught Exception» message php.net/manual/en/language.exceptions.php Code sampleif ($x == 0)
__toString() must not throw an exception
when i go to the browser at index.php, i get the following error Fatal error: Method MyDirectoryIterator::__toString() must not throw an exception in /home/oussama/Desktop/CoursesTraining/OOPInPHP/index.php on line 0
when i try to catch the exception, i get the same error, so how am i supposed to know what the exception is?
my home directory contains two files index.php and MyDirectoryIterator.inc.php, am using composer to handle autoload, and this is the source content:
_path = __DIR__ . '/' . $path; $this->_files = new RecursiveDirectoryIterator($path); $this->_files->setFlags( FileSystemIterator::UNIX_PATHS | FileSystemIterator::SKIP_DOTS ); $this->_rfiles = new RecursiveIteratorIterator($this->_files); > function __toString() < $output = ''; foreach($this->_rfiles as $file) < $output .= $file . '
'; > return $output; > >
when i copy the content of __toString, to __construct, the code behave as expected. so why i get that error, when i execute echo $files from my index.php?
this is how i solve it in case someone have the same probleme:
the exception was due to permission denied, to access some files in the listing, so i just add a try catch block inside __toString method.
function __toString() < $output = ''; try < foreach($this->_rfiles as $file) < $output .= $file . '
'; > > catch(Exception $e) <> return $output; >
the weird thing i’ve noticied, why that exception did not thrown when i remove __toString() from the class and i add its logic into the constructor? all the files are listed, with no exception ?
PHP exceptions thrown in error handler not caught by, I chose this title because I have the exact same problem as stated in here: PHP exceptions thrown in error handler are not caught by exception handler. The …
Unexpected Value exception
I am having below error in postman while i was teting my api. It shows slim application error in postman. Error Type: UnexpectedValueException
Message: Wrong number of segments
Do i need to modify the token or the JWT.php ?
decode.php in JWT.php
public static function decode($jwt, $key, array $allowed_algs = array()) < $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp; if (empty($key)) < throw new InvalidArgumentException('Key may not be empty'); >$tks = explode('.', $jwt); if (count($tks) != 3) < throw new UnexpectedValueException('Wrong number of segments'); >list($headb64, $bodyb64, $cryptob64) = $tks; if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) < throw new UnexpectedValueException('Invalid header encoding'); >if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) < throw new UnexpectedValueException('Invalid claims encoding'); >if (false === ($sig = static::urlsafeB64Decode($cryptob64))) < throw new UnexpectedValueException('Invalid signature encoding'); >if (empty($header->alg)) < throw new UnexpectedValueException('Empty algorithm'); >if (empty(static::$supported_algs[$header->alg])) < throw new UnexpectedValueException('Algorithm not supported'); >if (!in_array($header->alg, $allowed_algs)) < throw new UnexpectedValueException('Algorithm not allowed'); >if (is_array($key) || $key instanceof \ArrayAccess) < if (isset($header->kid)) < if (!isset($key[$header->kid])) < throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key'); >$key = $key[$header->kid]; > else < throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); >> // Check the signature if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) < throw new SignatureInvalidException('Signature verification failed'); >// Check if the nbf if it is defined. This is the time that the // token can actually be used. If it's not yet that time, abort. if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) < throw new BeforeValidException( 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf) ); > // Check that this token has been created before 'now'. This prevents // using tokens that have been created for later use (and haven't // correctly used the nbf claim). if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) < throw new BeforeValidException( 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat) ); > // Check if this token has expired. if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) < throw new ExpiredException('Expired token'); >return $payload; >
AuthController.php container = $container; > function auth($request,$response) < $input = $request->getParsedBody(); $user = Users::select('id','pword')->where('email','=',$input['email'])->first(); // verify email address. if(!$user) < $response->withStatus(404); return $response->withJson(['error' => true, 'message' => 'User does not exist.'],404); > // verify password. $salt = getenv('TMS_SALT'); if (!(sha1($salt.$input['password']) == $user->pword)) < $response->withStatus(401); return $response->withJson(['error' => true, 'message' => 'Password is incorrect.'],401); > $now = new \DateTime(); $future = new \DateTime("+120 minutes"); $server = $request->getServerParams(); $jti = (new Base62)->encode(random_bytes(16)); $payload = [ "iat" => $now->getTimeStamp(), // "exp" => $future->getTimeStamp(), "jti" => $jti, "sub" => $server["PHP_AUTH_USER"] ]; $token = JWT::encode($payload, getenv('JWT_SECRET'), "HS256"); $data = array( 'token' => $token, 'user_id'=>$user->id, // appod'expires' => $future->getTimestamp() ); $response->withStatus(200); return $response->withJson($data); > >
You should use third paramater in Decode Method to solve the Uncaught UnexpectedValueException: Algorithm not allowed
"; $decoded = JWT::decode($jwt, $key, array('HS256')); echo "After Encode = ".$decoded; > //call the funtion generate_token("santosh"); ?>
JWT **** = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.InNhbnRvc2gi.ZUyzpLH0FLB9VdRPS2CaQAqM_wKHjXP80moIzL-8u2o After Encode = santosh
PHP: set_exception_handler not working for error thrown, Use ‘include’ to work with the exception handler. There is a way to make it work. Make a php file that is bug-free and ‘includes’ two other PHP files: 1. Your error handler. 2. The file you want to debug. That way your error handling routines have been executed before the file to debug is being compiled. –