Created
November 3, 2015 16:33
-
-
Save carbontwelve/821b110fc725af0f00fc to your computer and use it in GitHub Desktop.
BasicAuth Middleware Laravel/Lumen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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