core icon indicating copy to clipboard operation
core copied to clipboard

Protecting api routes

Open sukhy-ghataore opened this issue 8 years ago • 1 comments

I have blade and eloquent running with flightphp along with JWT

I was wondering whether its possible to protect api routes

I currently have this at the moment. Is there a better way of achieving this >

$app->route('/api/*', function() use($app) {
		$request = $app->request();
		$NonAuthRoutes = [
			[ "route" => '/login', "ctrl" => 'Api\AuthController@postLogin' ],
			[ "route" => '/register', "ctrl" => 'Api\AuthController@postRegister' ],
			[ "route" => '/verify/register/@token', "ctrl" => 'Api\AuthController@verifyRegisterToken', "params" => ["token"] ],
		];
		foreach($NonAuthRoutes as $route) {
			$first = explode('@', $route['route'])[0];
			$second = str_replace("/api", "", $request->url);
			if( strncmp($first, $second, strlen($first)) === 0 ) {
				$ctrl = explode('@', $route['ctrl']);
				$class = $ctrl[0];
				$method = $ctrl[1];
				$params = isset($route['params']) ? $route['params'] : [];
				$intiClass = new $class($app);
				return call_user_func_array(array($intiClass, $method), $params);
			}
		}
		if( !$app->jwt() ) {
			return $app->json([
				"error"  => true,
				"message"  => "User has not been authenticated, api_key is not present",
				"current_route" => $app->router()->current()
			], 403);
		}
	})

sukhy-ghataore avatar Nov 16 '17 22:11 sukhy-ghataore

I check the JWT just after the autoload.php, before I handle the route. If the JWT is not valid, I reject a 401 error, otherwise, I create a variable (one array) in which I load the user rights for the connected user.

Then, inside each route, I check if the user rights allow the user to access that route. If the user is not allowed, it returns a 403 error, otherwise, the controller is executed.

You can see this concretely in my skeleton. I am not sure if this is the cleanest way but I do like this for several years and it works very well.

pierresh avatar May 23 '21 13:05 pierresh

So I guess what you're asking is can Flight handle middleware? We're building support for that with #514 Hopefully that gets you where you're hoping for.

n0nag0n avatar Jan 13 '24 18:01 n0nag0n