任何人都可以用示例解释 Laravel 5.2 多重身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34614753/
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-08 17:13:17  来源:igfitidea点击:

Can Anyone Explain Laravel 5.2 Multi Auth with Example

laravellaravel-5laravel-5.2laravel-authorization

提问by imrealashu

I am trying to authenticate usersand adminform usertable and admintable respectively. I am using the Usermodel as provided by laravel out of the box and created the same for Admin.I have added a guard key and provider key into auth.php.

我正在尝试分别对用户管理表单user表和admin表进行身份验证。我正在使用Userlaravel 提供的开箱即用的模型,并创建了相同的模型,因为Admin.我在其中添加了一个保护密钥和提供者密钥auth.php.

Guards

卫兵

'guards' => [
    'user' =>[
        'driver' => 'session',
        'provider' => 'user',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admin',
    ],
],  

Providers

供应商

'providers' => [
    'user' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'admin' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ]
],

Routes

路线

Route::group(['middleware' => ['web']], function () {
    // Login Routes.   
    Route::get('/admin/login','AdminAuth\AuthController@showLoginForm');
    Route::post('/admin/login','AdminAuth\AuthController@login');
    Route::get('/admin/logout','AdminAuth\AuthController@logout');

    // Registration Routes.
    Route::get('admin/register', 'AdminAuth\AuthController@showRegistrationForm');
    Route::post('admin/register', 'AdminAuth\AuthController@register');

    Route::get('/admin', 'AdminController@index');
});

I have created a directory called AuthAdminwhere Laravel's default AuthController.phpand PasswordController.phpfiles are present. (Namespace Modified accordingly)

我创建了一个名为AuthAdminLaravel 默认AuthController.phpPasswordController.php文件所在的目录。(命名空间相应修改)

First of all, in Laravel's docs mentioned that how to specify custom guard while authenticating like this which isn't working.
enter image description here

首先,在 Laravel 的文档中提到如何在像这样进行身份验证时指定自定义守卫是行不通的。
在此处输入图片说明

There's another method mentioned in Laravel's docs to use a guard which is not working too.

Laravel 的文档中提到了另一种方法来使用一个也不起作用的守卫。

enter image description here

在此处输入图片说明

It would be beneficial if someone could resolve the issues and correct me if I am wrong.

如果有人可以解决问题并在我错时纠正我,那将是有益的。

回答by imrealashu

After lots of digging and lots of questions & answers I have finally managed to work Laravel 5.2 Multi Auth with two table, So I'm writing Answer of my own Question.

经过大量的挖掘和大量的问题和答案,我终于设法使用两个表来使用 Laravel 5.2 Multi Auth,所以我正在写我自己的问题的答案。

How to implement Multi Auth in Larvel 5.2

如何在 Larvel 5.2 中实现多重身份验证

As Mentioned above. Two table adminand users

正如刚才提到的。两张桌子adminusers

Laravel 5.2 has a new artisancommand.

Laravel 5.2 有一个新artisan命令。

php artisan make:auth

php artisan make:auth

it will generate basic login/register route, viewand controllerfor usertable.

它会产生基本的登录/注册routeviewcontrolleruser表。

Make a admintable as userstable for simplicity.

为简单起见admin,将users桌子制作成桌子。

Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthControllerhere)

管理员控制器
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(注意:我只是从app/Http/Controllers/Auth/AuthController这里复制了这些文件)

config/auth.php

config/auth.php

//Authenticating guards
'guards' => [
    'user' =>[
        'driver' => 'session',
        'provider' => 'user',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admin',
    ],
],  

//User Providers
'providers' => [
    'user' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'admin' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ]
],  

//Resetting Password  
'passwords' => [
    'clients' => [
        'provider' => 'client',
        'email' => 'auth.emails.password',
        'table' => 'password_resets',
        'expire' => 60,
    ],
    'admins' => [
        'provider' => 'admin',
        'email' => 'auth.emails.password',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],  

route.php

route.php

Route::group(['middleware' => ['web']], function () {
    //Login Routes...
    Route::get('/admin/login','AdminAuth\AuthController@showLoginForm');
    Route::post('/admin/login','AdminAuth\AuthController@login');
    Route::get('/admin/logout','AdminAuth\AuthController@logout');

    // Registration Routes...
    Route::get('admin/register', 'AdminAuth\AuthController@showRegistrationForm');
    Route::post('admin/register', 'AdminAuth\AuthController@register');

    Route::get('/admin', 'AdminController@index');

});  

AdminAuth/AuthController.php

AdminAuth/AuthController.php

Add two methods and specify $redirectToand $guard

添加两个方法并指定$redirectTo$guard

protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
    if (view()->exists('auth.authenticate')) {
        return view('auth.authenticate');
    }

    return view('admin.auth.login');
}
public function showRegistrationForm()
{
    return view('admin.auth.register');
}  

it will help you to open another login form for admin

它将帮助您为管理员打开另一个登录表单

creating a middleware for admin

创建一个中间件 admin

class RedirectIfNotAdmin
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @return mixed
 */
public function handle($request, Closure $next, $guard = 'admin')
{
    if (!Auth::guard($guard)->check()) {
        return redirect('/');
    }

    return $next($request);
}

}

}

register middleware in kernel.php

注册中间件 kernel.php

 protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];

use this middleware in AdminControllere.g.,

AdminController例如使用这个中间件,

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    public function __construct(){
        $this->middleware('admin');
   }
public function index(){
        return view('admin.dashboard');
    }
}

That's all needed to make it working and also to get json of authenticated admin use
Auth::guard('admin')->user()

这是使其正常工作以及获取经过身份验证的管理员使用的 json 所需的全部内容
Auth::guard('admin')->user()

Edit - 1
We can access authenticated user directly using
Auth::user()but if you have two authentication table then you have to use

编辑 - 1
我们可以使用直接访问经过身份验证的用户,
Auth::user()但是如果您有两个身份验证表,那么您必须使用

Auth::guard('guard_name')->user()  

for logout

登出

Auth::guard('guard_name')->user()->logout()

for authenticated user json

对于经过身份验证的用户 json

Auth::guard('guard_name')->user()  

Edit 2

编辑 2

Now you can download Laravel 5.2 Multiauth implemented Project http://imrealashu.in/code/laravel/multi-auth-with-laravel-5-2-2/

现在你可以下载 Laravel 5.2 Multiauth 实现的项目http://imrealashu.in/code/laravel/multi-auth-with-laravel-5-2-2/

回答by Sworrub Wehttam

In case this helps anyone, and this may just be due to my lack of understanding of middleware, here's what I had to do to get this working (in addition to the steps taken by @imrealashu)...

如果这对任何人有帮助,这可能只是由于我对中间件缺乏了解,这是我必须做的才能使其正常工作(除了@imrealashu 采取的步骤)...

In route.php:

route.php

Route::get('/admin', [
  'middleware' => 'admin',
  'uses' => 'AdminController@index'
]);

This is in the webmiddleware group. Before this I tried putting it in a separate adminmiddleware group and even in an auth:admingroup but this didn't work, it only worked for me when I specified the middleware as admin on the route itself. I have no idea why this is but I hope it saves others from pulling their hair out like I did.

这是在web中间件组中。在此之前,我尝试将它放在一个单独的admin中间件组中,甚至放在一个auth:admin组中,但这不起作用,只有当我将中间件指定为路由本身的管理员时,它才对我有用。我不知道为什么会这样,但我希望它可以避免其他人像我一样拔头发。

回答by Sky

It's very easy in laravel 5.6. Just go to config/auth.phpand add this line in providersarray:

在 Laravel 5.6 中这很容易。只需转到config/auth.php并将此行添加到providers数组中:

'admins' => [
   'driver' => 'database',
   'table' => 'admin_table'
]

Note that we used databasefor driver not eloquent.

请注意,我们用于database驱动程序 not eloquent

Now add this to guardsarray:

现在将其添加到guards数组中:

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

Now we're done! Use this when working with admins table:

现在我们完成了!在使用 admins 表时使用它:

Auth::guard('admin_guard')->User();

Cheers.

干杯。