Hello guys !
So in Laravel 4 we could do
Route::filter('auth.basic', function()
{
return Auth::basic('username');
});
But now it's not possible, and the doc doesn't give a clue about how to. So can anyone help ?
Thanks !
Auth::user() — You can check if a user is authenticated or not via this method from the Auth Facade. It returns true if a user is logged-in and false if a user is not. Check here for more about how Facades work in Laravel.
How do I enable authentication in Laravel? You need to Install the laravel/ui Composer bundle and run php artisan ui vue –auth in a new Laravel application. After migrating your database, open http://your-app.test/register or any other URL that's assigned to your application on your browser.
Create a new custom middleware using the same code as the default one:
https://github.com/laravel/framework/blob/5.0/src/Illuminate/Auth/Middleware/AuthenticateWithBasicAuth.php
and override the default 'email' field like:
return $this->auth->basic('username') ?: $next($request);
Using Laravel 5.7, the handle method looks like this:
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @param string|null $field
* @return mixed
*/
public function handle($request, Closure $next, $guard = null, $field = null)
{
return $this->auth->guard($guard)->basic($field ?: 'email') ?: $next($request);
}
If you look at the function definition, can specify the $field
value.
According to Laravel's documentation you can provide middleware parameters:
Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:
Using the following I was able to specify my field to use in basic auth:
Route::middleware('auth.basic:,username')->get('/<route>', 'MyController@action');
The :,username
syntax might be a little confusing. But if you look at the function definition:
public function handle($request, Closure $next, $guard = null, $field = null)
You will notice there are two paramters after $next
. $guard
is null
by default and I wanted it remain null/empty so I omit the value and provide an empty string. The next parameter (separated by a comma like the documentation says) is the $field
I'd like to use for basic auth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With