From 2489c9de95f2e179309f7b441152ab761b89e3d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julio=20Napuri=CC=81?= Date: Thu, 6 Mar 2014 17:26:06 -0500 Subject: [PATCH] HTTP Basic Authentication Middleware for Slim Framework --- src/Slim/Middleware/HttpBasicAuth.php | 81 +++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/Slim/Middleware/HttpBasicAuth.php diff --git a/src/Slim/Middleware/HttpBasicAuth.php b/src/Slim/Middleware/HttpBasicAuth.php new file mode 100644 index 0000000..9c329eb --- /dev/null +++ b/src/Slim/Middleware/HttpBasicAuth.php @@ -0,0 +1,81 @@ + + */ +class HttpBasicAuth extends \Slim\Middleware +{ + /** + * @var string + */ + protected $realm; + + /** + * @var string + */ + protected $username; + + /** + * @var string + */ + protected $password; + + /** + * @var string + */ + protected $route; + + /** + * Constructor + * + * @param string $username The HTTP Authentication username + * @param string $password The HTTP Authentication password + * @param string $realm The HTTP Authentication realm + */ + public function __construct($username, $password, $realm = 'Protected Area', $route = '') + { + $this->username = $username; + $this->password = $password; + $this->realm = $realm; + $this->route = $route; + } + + /** + * Call + * + * This method will check the HTTP request headers for previous authentication. If + * the request has already authenticated, the next middleware is called. Otherwise, + * a 401 Authentication Required response is returned to the client. + */ + public function call() + { + $request = $this->app->request; + + if (false !== strpos($request->getPath(), $this->route)) { + + $req = $this->app->request(); + $res = $this->app->response(); + $authUser = $req->headers('PHP_AUTH_USER'); + $authPass = $req->headers('PHP_AUTH_PW'); + + if ($authUser && $authPass && $authUser === $this->username && $authPass === $this->password) { + $this->next->call(); + } else { + $res->status(401); + $res->header('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realm)); + } + + return; + } + $this->next->call(); + + + } +} \ No newline at end of file