Laravel 自定义多重身份验证

Posted

技术标签:

【中文标题】Laravel 自定义多重身份验证【英文标题】:Laravel Custom Multi Authentication 【发布时间】:2020-03-11 07:42:31 【问题描述】:

我正在创建一个具有自定义多重身份验证的 laravel 应用程序。我正在关注这篇文章进行多重身份验证。 https://pusher.com/tutorials/multiple-authentication-guards-laravel

我已经创建了登录和注册控制器定义的守卫和提供者,一切正常,我能够注册用户并登录他们。我已经创建了一个页面 (http://127.0.0.1:8000/admin),该页面只有在管理员登录时才能访问,但每个人都可以访问此 url。下面是我的代码,

登录控制器代码

public function __construct()

     $this->middleware('guest')->except('logout');
        $this->middleware('guest:admin')->except('logout');
        $this->middleware('guest:writer')->except('logout');



public function showAdminLoginForm()

    return view('auth.login', ['url' => 'admin']);


public function adminLogin(Request $request)

    $this->validate($request, [
        'email'   => 'required|email',
        'password' => 'required|min:6'
    ]);

    if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request>password], $request->get('remember'))) 

        return redirect()->intended('/admin');
    
    return back()->withInput($request->only('email', 'remember'));

注册控制器代码

     public function __construct()
    
        $this->middleware('guest');
            $this->middleware('guest:admin');
            $this->middleware('guest:writer');


    

     public function showAdminRegisterForm()
    
        return view('auth.register', ['url' => 'admin']);
    
protected function createAdmin(Request $request)
    
        $this->validator($request->all())->validate();
        $admin = Admin::create([
            'name' => $request['name'],
            'email' => $request['email'],
            'password' => Hash::make($request['password']),
        ]);
        return redirect()->intended('login/admin');
    

管理员型号代码

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Database\Eloquent\Model;

class admin extends Authenticatable 



     use Notifiable;

        protected $guard = 'admin';

        protected $fillable = [
            'name', 'email', 'password',
        ];

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

处理程序.php

  protected function unauthenticated($request, AuthenticationException $exception)
    
        if ($request->expectsJson()) 
            return response()->json(['error' => 'Unauthenticated.'], 401);
        
        if ($request->is('admin') || $request->is('admin/*')) 
            return redirect()->guest('/login/admin');
        
        if ($request->is('writer') || $request->is('writer/*')) 
            return redirect()->guest('/login/writer');
        
        return redirect()->guest(route('login'));
    

重定向ifAuthenticated.php

public function handle($request, Closure $next, $guard = null)

    if ($guard == "admin" && Auth::guard($guard)->check()) 
            return redirect('/admin');
        
        if ($guard == "writer" && Auth::guard($guard)->check()) 
            return redirect('/writer');
        
        if (Auth::guard($guard)->check()) 
            return redirect('/home');
        

        return $next($request);
    

Admin.blade.php 查看

   <html>
    <head>
        <title>admin page </title>
    </head>
    <body>

    <h1> hi bosss </h1>
    </body>
    </html>

//Auth.php

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

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


          'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'writer' => [
            'driver' => 'session',
            'provider' => 'writers',
        ],
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\admin::class,
    ],
    'writers' => [
        'driver' => 'eloquent',
        'model' => App\writer::class,
    ],

//web.php

  <?php
Route::view('/', 'welcome');
Auth::routes();

Route::get('/login/admin', 'Auth\LoginController@showAdminLoginForm');
Route::get('/login/writer', 'Auth\LoginController@showWriterLoginForm');
Route::get('/register/admin', 'Auth\RegisterController@showAdminRegisterForm');
Route::get('/register/writer', 'Auth\RegisterController@showWriterRegisterForm');

Route::post('/login/admin', 'Auth\LoginController@adminLogin');
Route::post('/login/writer', 'Auth\LoginController@writerLogin');
Route::post('/register/admin', 'Auth\RegisterController@createAdmin');
Route::post('/register/writer', 'Auth\RegisterController@createWriter');

Route::view('/home', 'home')->middleware('auth');
Route::view('/admin', 'admin');
Route::view('/writer', 'writer');

请提出建议。

【问题讨论】:

请提供您的 auth.php 和 web.php 你是如何定义这条路由到admin url的?你给它分配了什么中间件,等等? @lagbox 你能提供更多关于你的问题的解释吗? 显示您为 URL admin 定义的路由以及它指向的控制器 @lagbox 请使用 web.php 代码回答上述问题。我已经编辑过了。 【参考方案1】:

您应该将 auth:admin 中间件分配给您希望仅限管理员使用的路由:

Route::view('admin', 'admin')->middleware('auth:admin');

Laravel 6.x Docs - Authentication - Protecting Routes - Specifying A Guard

【讨论】:

【参考方案2】:

我认为有两个单独的表不值得useradmin。 我发现多重身份验证的最佳方法是: https://www.itsolutionstuff.com/post/laravel-6-multi-auth-authentication-tutorialexample.html

【讨论】:

以上是关于Laravel 自定义多重身份验证的主要内容,如果未能解决你的问题,请参考以下文章

我正在尝试为 user 和 admin 实现 laravel 5.2 多重身份验证。但是未定义身份验证用户提供程序 [] 错误给出

如何在 laravel 5.2 中使用多重身份验证 [关闭]

每次我输入错误密码时,使用 JWT 身份验证的 Laravel 多重身份验证

Laravel 多重身份验证::尝试

Laravel - 具有多重身份验证的未经身份验证的重定向问题

Laravel 多重身份验证 |路由中间件