Skip to content

Instantly share code, notes, and snippets.

@kevyworks
Last active November 30, 2018 14:06
Show Gist options
  • Save kevyworks/e69e61d5ec55fad49e8b92900d9f38f5 to your computer and use it in GitHub Desktop.
Save kevyworks/e69e61d5ec55fad49e8b92900d9f38f5 to your computer and use it in GitHub Desktop.
Custom Basic Auth
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
/**
* Class BasicAuth
*
* Usage:
*
* Route::post('webhook', 'WebhookController@webhook')
* ->middleware('auth.basic:myconfig.auth'); // return [ 'auth' => 'demo,demo' ]
*
* Route::get('/demo', 'DemoController@index')
* ->middleware('auth.basic:demo,demo');
*
* Replace Kernel or Add new entry
*
* 'auth.basic' => \App\Http\Middleware\BasicAuth::class
*
* @class BasicAuth
* @extends Illuminate\Auth\Middleware\AuthenticateWithBasicAuth
* @package App\Http\Middleware
*/
class BasicAuth extends AuthenticateWithBasicAuth
{
/**
* Get Basic credentials
*
* @return object
*/
private function getAuth()
{
return (object)[
'username' => request()->getUser(),
'password' => request()->getPassword()
];
}
/**
* Check Basic Auth
*
* @param mixed $key Username or config path.
* @param mixed $password Password passed inline
* @return boolean|null
* @throws UnauthorizedHttpException
*/
private function checkAuth($key, $password)
{
$auth = $this->getAuth();
if ($key) {
if ($password === null) {
$cred = explode(',', config($key, ','));
$key = $cred[0];
$password = $cred[1] ?? '';
}
if (!($auth->username === $key && $auth->password === $password)) {
throw new UnauthorizedHttpException('Basic', 'Invalid credentials.');
}
return null;
} elseif ($key === null && $password === null) {
return $this->auth->guard()->basic();
}
return false;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param mixed $username
* @param mixed|null $password
* @return mixed
*/
public function handle($request, Closure $next, $username = null, $password = null)
{
return $this->checkAuth($username, $password) ?: $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment