Skip to content

Instantly share code, notes, and snippets.

@FlorianWeigang
Last active August 14, 2023 02:26
Show Gist options
  • Save FlorianWeigang/2fe04b2f3df85f7491cf to your computer and use it in GitHub Desktop.
Save FlorianWeigang/2fe04b2f3df85f7491cf to your computer and use it in GitHub Desktop.
static laravel basic.auth with username and password in config file
<?php
/**
* change this definition in filters.php.
*
* the code checks if the auth parameters matches the credentials in your config file, if not
* a WWW-Authenticate Header will be send to the client.
*/
Route::filter('auth.basic', function () {
$login = false;
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
// check credentials from config.
if (
$_SERVER['PHP_AUTH_USER'] === Config::get('app.username') &&
$_SERVER['PHP_AUTH_PW'] === Config::get('app.password')
) {
$login = true;
}
}
if ($login === false) {
return Response::make('Invalid credentials.', 401, ['WWW-Authenticate' => 'Basic']]);
}
});
@Gzerox
Copy link

Gzerox commented Aug 10, 2015

I was looking for this, thanks !

that code was also working for Laravel v5.1.

Here the same code , just mini-syntax update:
Middleware:

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Closure                 $next
 *
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $logged = false;

    //check if request has authorization header
    if ($request->header('PHP_AUTH_USER', null) && $request->header('PHP_AUTH_PW', null)) {

        $username = $request->header('PHP_AUTH_USER');
        $password = $request->header('PHP_AUTH_PW');

        if ($username === Config::get('app.username') && $password === Config::get('app.password')) 
            $logged = true;

    }

    //user not logged, request authentication
    if ($logged === false) {

        $headers = ['WWW-Authenticate' => 'Basic'];
        return response()->make('Invalid credentials.', 401, $headers);

    } else //if succesfull logged, proceed with request
        return $next($request);

}

@FlorianWeigang
Copy link
Author

great, thank you @Gzerox :)

@Shareed2k
Copy link

public function handle($request, Closure $next)
    {
        if ($request->getUser() === Config::get('sso.username') && $request->getPassword() === Config::get('sso.password'))
            return $next($request);

        return new Response('Invalid credentials.', 401, ['WWW-Authenticate' => 'Basic']);

    }

@androzd
Copy link

androzd commented Aug 24, 2018

@hasnatbabur
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment