Laravel多认证和授权资源

时间:2019-01-29 14:26:59

标签: php laravel authentication policy guard

我在以下情况下遇到问题,希望在这里找到建议:

我已经安装了Laravel 5.7并运行了make:auth作为身份验证支架。本机用户模型已删除,而我使用的是两个自定义模型“客户”和“管理员”(迁移已相应更改)。

管理员模型:     

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Traits\FormatUserdata;

class Admin extends Authenticatable
{
    use Notifiable, FormatUserdata;

    protected $guard = 'admin';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname', 'lastname', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

客户模型:     

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Traits\FormatUserdata;

class Customer extends Authenticatable
{
    use HasApiTokens, Notifiable, FormatUserdata;

    protected $guard = 'customer';

    protected $fillable = [
        'firstname', 'lastname', 'email', 'company', 'address', 'zip', 'city', 'country', 'vatid', 'customer_no', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function licenses()
    {
        return $this->hasMany('App\License');
    }
}

因此,我必须验证来自两个不同模型和表的用户。为了使它起作用,我像这样更改了config / auth.php:     

return [
    'defaults' => [
        'guard' => 'customer',
        'passwords' => 'customers',
    ],

    'guards' => [
        'customer' => [
            'driver' => 'session',
            'provider' => 'customers',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'admins',
        ],
    ],

    'providers' => [
        'customers' => [
            'driver' => 'eloquent',
            'model' => App\Customer::class,
        ],

        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],
    ],

    'passwords' => [
        'customers' => [
            'provider' => 'customers',
            'table' => 'password_resets',
            'expire' => 60,
        ],

        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

对于我的客户模型,我设置了一个资源控制器,该控制器受资源策略以及index方法的auth中间件保护:     

namespace App\Http\Controllers;

use App\Customer;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:admin')->only('index');
        $this->authorizeResource(Customer::class);
    }

    public function show(Customer $customer)
    {}

    ...shortened

}

这是我在此控制器中引用的策略:     

namespace App\Policies;

use App\Customer;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Foundation\Auth\User;

class CustomerPolicy
{
    use HandlesAuthorization;

    public function view(User $user, Customer $customer)
    {
        return true;
    }

}

我的路线没有应用任何其他中间件。

这是问题所在:

当我使用默认后卫“客户”的用户访问路由/ customers / 1时,一切都会按预期进行(没有错误)。但是,当我尝试与管理员用户访问该路由时,会收到403未经授权的响应。奇怪的是,当我尝试使用

检查视图中的权限时
@can('view', App\Customer::findOrFail(3))

该政策正常运行。我发现以管理员身份访问路由时根本没有调用该策略的view方法。我对laravel代码进行了深入研究,我很确定该问题与以下事实有关:默认情况下是客户防护,而默认情况下是用户解析器。

有人知道如何解决该问题吗?

谢谢! 安德烈亚斯(Andreas)

编辑:

这是我的AuthServiceProvicer.php:     

namespace App\Providers;

use App\Policies\CustomerPolicy;
use App\Customer;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Customer::class => CustomerPolicy::class
    ];

    public function boot()
    {
        $this->registerPolicies();
    }
}

这是我的路线/web.php     

Route::get('/', function () {
    return view('welcome');
});

Auth::routes(['register' => false]);

Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('/', function () {
        return redirect( route('admin.dashboard') );
    });

    Route::get('dashboard', 'AdminController@dashboard')->name('dashboard');
    Route::get('login', 'Auth\AdminLoginController@showLoginForm')->name('login');
    Route::post('login', 'Auth\AdminLoginController@login')->name('login.post');
    Route::post('logout', 'Auth\AdminLoginController@logout')->name('logout');

    Route::post('password/email', 'Auth\AdminForgotPasswordController@sendResetLinkEmail')->name('password.email');
    Route::get('password/reset', 'Auth\AdminForgotPasswordController@showLinkRequestForm')->name('password.request');
    Route::post('password/reset', 'Auth\AdminResetPasswordController@reset')->name('password.update');
    Route::post('password/reset/{token}', 'Auth\AdminResetPasswordController@showResetForm')->name('password.reset');

    Route::resource('customers', 'CustomerController');
});

Route::prefix('backend')->name('backend.')->group(function () {
    Route::get('/', function () {
        return redirect( route('backend.dashboard') );
    });
    Route::get('dashboard', 'BackendController@dashboard')->name('dashboard');
    Route::resource('customers', 'CustomerController')->except([
        'index'
    ]);

});

因此,对于客户来说,我使用的是路由/ backend / customer / {customer},对于管理员来说,我使用的是路由/ admin / customer / {customer}

1 个答案:

答案 0 :(得分:0)

经过进一步的研究,我发现了这篇很棒的博客文章

https://medium.com/@JinoAntony/multi-user-authentication-using-guards-in-laravel-5-6-f18b4e61bdde

这里的重要步骤是创建一个额外的中间件“ AssignGuard”,该中间件根据所使用的路由来设置防护。