Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - how to use basic auth with username in place of email?

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 !

like image 716
Jeremy Belolo Avatar asked May 20 '15 23:05

Jeremy Belolo


People also ask

What is auth ()- user () in Laravel?

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 login with Auth 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.


2 Answers

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);
like image 191
Davor Minchorov Avatar answered Oct 22 '22 14:10

Davor Minchorov


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.

like image 42
domdambrogia Avatar answered Oct 22 '22 13:10

domdambrogia