Skip to content

Instantly share code, notes, and snippets.

@carbontwelve
Created November 3, 2015 16:33
Show Gist options
  • Select an option

  • Save carbontwelve/821b110fc725af0f00fc to your computer and use it in GitHub Desktop.

Select an option

Save carbontwelve/821b110fc725af0f00fc to your computer and use it in GitHub Desktop.
BasicAuth Middleware Laravel/Lumen
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
class BasicWebAuth
{
/**
* Name of the realm
*
* @var string
*/
private $realm = 'Restricted area';
/**
* Valid Users
* @var array
*/
private $users = array(
'username' => 'password'
);
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// 1. Check the user is authenticated for this session
if ( false === $request->session()->get('isAuthenticated', false) )
{
if ( false === $request->header('PHP_AUTH_USER', false) )
{
// Save their destination and return headers for BasicAuth
$request->session()->put('intendedDestination', $request->getUri());
return $this->notAuthorisedResponse();
}else{
// If user is not found
if ( ! isset($this->users[$request->header('PHP_AUTH_USER')])){ return $this->notAuthorisedResponse(); }
// If password is incorrect
if ( $this->users[$request->header('PHP_AUTH_USER')] !== $request->header('PHP_AUTH_PW') ){ return $this->notAuthorisedResponse(); }
// Else Log them in
$request->session()->put('isAuthenticated', true);
}
}
return $next($request);
}
private function notAuthorisedResponse()
{
/** @var Response $response */
$response = new Response();
$response->header('WWW-Authenticate', 'Basic realm="'. $this->realm .'"');
$response->setStatusCode(401);
$response->setContent('401: You are not authorised');
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment