面向初学者的多身份验证laravel 5.6

时间:2018-08-26 17:13:08

标签: laravel authentication laravel-5.6

有人可以帮助我如何在laravel 5.6中进行多重身份验证吗,我已经读过此How to create multi auth in laravel 5.6? 但还是不明白。请帮助我。

1 个答案:

答案 0 :(得分:0)

这个家伙很摇晃...我学会了如何使用此youtube视频进行多重身份验证,虽然有点长,但是如果您想要的话,它肯定会让您对Admin和User进行身份验证。

https://www.youtube.com/watch?v=iKRLrJXNN4M&list=PLwAKR305CRO9S6KVHMJYqZpjPzGPWuQ7Q

这是我为本教程视频制作的备忘单。当您厌倦了在视频上键入所有内容时,请参考它。但是,我强烈建议您观看视频,仅看这些说明可能还不够。

基本身份验证和管理员模型

php artisan make:auth

php artisan make:migration create_admins_table --create=admins
  

数据库/迁移/ ??? _ create_admins_table.php

public function up()
{
    Schema::create('admins', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

将用户模型复制到管理模型

User.php

Admin.php

保护auth.php中的管理员

  

config / auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'admin-api' => [
        'driver' => 'token',
        'provider' => 'admins',
    ],
],
**Create provider for Admin**
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ]
],
**Create password resets for admin**
'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
    ],
    'admins' => [
        'provider' => 'admins',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],

将Admin Guard应用于管理模型

  

App / Admin.php

protected $guard = 'admin’;

设置AdminContoller

重复的HomeController-> AdminController

  

App / Http / Controllers / AdminController.php

public function __construct()
{
    $this->middleware('auth:admin');
}

创建AdminLoginController

php artisan make:controller Auth/AdminLoginController

进行管理员登录视图

重复的login.blade.php-> admin-login.blade.php

resources / views / admin-login.blade.php

登录->管理员登录

route(‘login’) -> route(‘admin.login.submit’)

管理路由设置

  

routes / web.php

Route::prefix('admin')->group(function() {
    Route::get('/', 'AdminController@index’)->name(‘admin.dashboard');
    Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
});

进行AdminLoginController登录

  

app / http / controllers / Auth / AdminLoginController.php

public function __construct()
{
    $this->middleware('guest:admin', ['except' => ['logout']]);
}

public function showLoginForm()
{
    return view('auth.admin-login');
}

public function login(Request $request)
{
    // Validate the form adata
    $this->validate($request, [
        'email' => 'required|email',
        'password' => 'required|min:6'
    ]);
    //Attempt to log the user in
    if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
        //if sucessful, the redirect to their
        return redirect()->intended(route('admin.dashboard'));
    }
    //if unseccessful
    return redirect()->back()->withInput($request->only('email', 'remember'));
}

public function logout()
{
    Auth::guard('admin')->logout();
    return redirect('/');
}

解决重定向错误1

    / li导致/ admin进入/ login时出错
  • 使用异常处理程序解决它。在未经身份验证的状态下,如果Guard是admin,则将其重定向到/ admin / login,在其他情况下,将其重定向到/ login
  

App / Exceptions / Handler.php

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'unauthenticated'], 401);
    }

    $guard = array_get($exception->guards(),0);

    switch ($guard) {
        case 'admin':
            $login = 'admin.login';
            break;
        default:
            $login = 'login';
            break;
    }

    return redirect()->guest(route($login));
}

解决重定向错误2

  • 受访客中间件保护的页面仅指向/ home
  • 以用户身份登录时,输入/ admin将重定向到/ home,这是由于仅识别guest:user而引起的。因此,我们应该修复RedirectIfAuthenticated,以便我们的应用程序也可以识别guest:admin。
  

App / Http / Middleware / RedirectIfAuthenticated

public function handle($request, Closure $next, $guard = null)
{
    switch($guard) {
        case 'admin':
            if(Auth::guard($guard)->check()) {
                return redirect()->route('admin.dashboard');
            }
            break;
        default:
            if(Auth::guard($guard)->check()) {
                return redirect()->route('/home');
            }
    }

    return $next($request);
}

更新您的laravel项目的配置缓存

php artisan config:cache

希望它会有所帮助:)