我有一条路线:
Route::get('/', array('before' => 'auth.basic', function() {
return Response::json(
array(
'name' => 'John Smith',
'age' => 42
)
);
}));
我想要的是将where active= 1
添加到身份验证查询中。
我知道我可以向Auth::attempt()
添加额外的条件,但我不知道如何使用Auth::basic()
来做到这一点。
有两种方法可以做到这一点。
1.修改筛选器并使用Auth::attempt()
这就是简单的方法。转到app/filter.php
,将auth.basic条目更改为此
Route::filter('auth.basic', function()
{
if(Auth::check()) return; // already logged in
if(Auth::attempt(array(
'email' => Request::getUser(),
'password' => Request::getPassword(),
'active' => 1))){
return;
}
$headers = array('WWW-Authenticate' => 'Basic');
return Response::make('Invalid credentials.', 401, $headers);
});
这基本上就是Laravel Guard类在调用Auth::basic()
时所做的(显然除了"活动"部分)
2.扩展Auth
现在这就是";更优雅";尽管我不知道这对你来说是否真的值得。我也不会详细描述它。
要扩展Laravel Auth,您可以使用Auth::extend()
。这里有一个例子:
Auth::extend('my_driver', function() {
$model = Config::get('auth.model');
$provider = new Illuminate'Auth'EloquentUserProvider(App::make('hash'), $model);
return new MyGuard($provider, App::make('session.store'));
});
MyGuard
类将扩展Illuminate'Auth'Guard
并覆盖getBasicCredentials()
方法。最后在config/auth.php
中设置'driver' => 'my_driver'
如果你选择了第二种方法,并且需要更多帮助,请写一条评论。。。
我是如何做到的(Laravel 5.8):
SessionGuard的方法basic
和basicOnce
接受两个参数:$field
,您可以在其中设置username列,$extraConditions
,您可以设置额外的条件。
您可以扩展AuthenticateWithBasicAuth
并覆盖handle
方法以获得类似的内容
class CustomBasicAuth extends AuthenticateWithBasicAuth
public function handle($request, Closure $next, $guard = null, $field = null)
{
$this->auth->guard($guard)->basic('email', ['active' => 1]);
return $next($request);
}
不要忘记注册和使用新的中间件。