如何在 Laravel 中为 auth 控制器设置新的保护

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38978522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:19:06  来源:igfitidea点击:

how to set new guard for auth controller in laravel

phplaravellaravel-5

提问by Matej

I want to make multiple authentication in my laravel project.

我想在我的 Laravel 项目中进行多重身份验证。

I create new guard "admin" in my auth.php file but I don't know how to set new created guard in my authcontroller.

我在 auth.php 文件中创建了新的守卫“admin”,但我不知道如何在我的 authcontroller 中设置新创建的守卫。

It always use "defaults" settings from my auth.php:

它总是使用我的 auth.php 中的“默认”设置:

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

回答by Gaurav

1) If you wish to use newly created adminguard throughout the application, you can change the value in defaultsof config file.

1) 如果您希望在admin整个应用程序中使用新创建的守卫,您可以更改配置文件默认值中的



2) If it is only about AuthControllerthat uses Laravel's in built Auth system, you can add this line in the AuthController.phpand PasswordController.php:

2) 如果只是AuthController使用 Laravel 内置的 Auth 系统,你可以在AuthController.phpPasswordController.php 中添加这一行:

protected $guard = 'admin';

Ref - Check Guard Customizationhere

Ref -在此处检查防护定制



3) If you wish to you a guard other than default one for any Auth related task, you can specify it manually like this :

3)如果您希望为任何与身份验证相关的任务提供除默认值之外的守卫,您可以像这样手动指定它:

// For route middleware
Route::get('profile', [
    'middleware' => 'auth:admin',
    'uses' => 'ProfileController@show'
]);

// For manually logging the user in
if (Auth::guard('admin')->attempt($credentials)) {
    // Authenticated...
}

// To login specific user using eloquent model
Auth::guard('admin')->login($user);

// For getting logged in user
Auth::guard('admin')->user();

// To check if user is logged in
if (Auth::guard('admin')->check()) {
    // Logged in
}

Ref - https://laravel.com/docs/5.2/authentication

参考 - https://laravel.com/docs/5.2/authentication

回答by BraDev

Laravel 5.4+ uses the following in any Auth Controller:

Laravel 5.4+ 在任何身份验证控制器中使用以下内容:

use Illuminate\Support\Facades\Auth;

protected function guard(){
   return Auth::guard('guard-name');
}

回答by BraDev

You have to also register the guard in the config\auth.php

您还必须在 config\auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

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

admin is the guard name, provider is the TABLE-NAME

admin 是警卫名称,provider 是 TABLE-NAME