Laravel Multi Auth-管理员防护 [英] Laravel Multi Auth - Admin Guard

查看:66
本文介绍了Laravel Multi Auth-管理员防护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在拉拉维尔(Laravel)有两个警卫

I have two guards in laravel

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

        //Our Admin custom driver
        'web_admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
    ],

和提供者

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

     //Admin user provider
      'admins' => [
          'driver' => 'eloquent',  //We are using eloquent model
          'model' => App\Admin::class,
      ],
],

默认值为

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

当我以管理员身份登录并尝试访问用户个人资料时,它要求我以正常用户身份登录.但是我正在寻找的是,管理员应该能够以管理员登录名访问整个站点.

When i log in as admin and try to access the user profile it asks me to login as user which is normal. But what im looking for is, admin should be able to access whole site as admin login.

我之所以选择rbac上的多身份验证是因为我有5种类型的用户,每种类型都有不同的注册字段和登录名.每个用户也都有一套工具.

The reason i choose multi auth over rbac is because i have 5 types of users and each have different registration fields and login. Each user have a set of tools too.

因此,我希望管理员也可以访问所有警卫.

So i want admin guard to be able to access all guards too.

业务后卫只能访问用户后卫.

Business guard to be able to access only users guard.

App/Http/Controllers/AdminAuth/LoginController

App/Http/Controllers/AdminAuth/LoginController

<?php

//LoginController.php

namespace App\Http\Controllers\AdminAuth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

//Class needed for login and Logout logic
use Illuminate\Foundation\Auth\AuthenticatesUsers;

//Auth facade
use Auth;

class LoginController extends Controller
{
    //Where to redirect admin after login.
    protected $redirectTo = '/admin/home';

    //Trait
    use AuthenticatesUsers;

    //Custom guard for admin
    protected function guard()
    {
      return Auth::guard('web_admin');
    }

    //Shows admin login form
   public function showLoginForm()
   {
       return view('admin.auth.login');
   }
}

App/Http/Controllers/Auth/LoginController

App/Http/Controllers/Auth/LoginController

<?php

namespace App\Http\Controllers\Auth;
use Socialite;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return \Illuminate\Http\Response
     */
      public function redirectToProvider($social)
      {
          return Socialite::driver($social)->redirect();
      }

      /**
       * Obtain the user information from GitHub.
       *
       * @return \Illuminate\Http\Response
       */
      public function handleProviderCallback($social)
      {
          $user = Socialite::driver($social)->user();

          // $user->token;
      }
}

类似地,我也在App/Https/Middleware/AuthenticateAdmin.php中也为管理员创建了中间件

Similarly i have created middleware for admin too in App/Https/Middleware/AuthenticateAdmin.php

<?php

//AuthenticateAdmin.php

namespace App\Http\Middleware;

use Closure;

//Auth Facade
use Auth;

class AuthenticateAdmin
{
   public function handle($request, Closure $next)
   {
       //If request does not comes from logged in admin
       //then he shall be redirected to admin Login page
       if (! Auth::guard('web_admin')->check()) {
           return redirect('/admin/login');
       }

       return $next($request);
   }
}

并RedirectIfAdminAuthenticated

And RedirectIfAdminAuthenticated

<?php

//RedirectIfAdminAuthenticated.php

namespace App\Http\Middleware;

use Closure;

//Auth Facade
use Auth;

class RedirectIfAdminAuthenticated
{

  public function handle($request, Closure $next)
  {
      //If request comes from logged in user, he will
      //be redirect to home page.
      if (Auth::guard()->check()) {
          return redirect('/home');
      }

      //If request comes from logged in admin, he will
      //be redirected to admin's home page.
      if (Auth::guard('web_admin')->check()) {
          return redirect('/admin/home');
      }
      return $next($request);
  }
}

RedicrectIfAuthenticated

RedicrectIfAuthenticated

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * 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 = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        return $next($request);
    }
}

推荐答案

进一步了解我们的信件

1.

如果您有许多类型的用户...所以我建议您更改逻辑并将管理员"也设置为用户" ...删除管理员,并在用户中添加类型"字段或类似内容...并使用字段来检查用户是否为admin或有权访问系统的某些部分...以及用户类型"是否为"admin",以便他也将有权访问所有部分.

If you have many types of users... so i suggest you to change your logic and make the Admin as User too... remove the admins and in the users add field "type" or something like that... and work with field to check if user is admin or have permission / access to some parts of the system... and if the user "type" is "admin" so he will have access to all parts too.

所以您的意思是删除多认证并使用RBAC.但是我有一个要求,我需要使用多重身份验证,每个警卫都有自己的RBAC.例如,管理员警卫角色是经理,支持人员等等.业务警卫角色是供应商,卖方等.

so you mean remove multi auth and go for RBAC. But i have a requirement where i need to use multi auth and each guard has their own RBAC For example, admin guard roles are manager, support and so. Business guard roles are vendors, sellers and so.

  • 是的,这就是我的意思.我在开发的其中一个系统上做过类似的事情,并增加了一个防护,因此所有已登录"的路由都通过了(例如auth),并且在此检查请求的溃败和操作并检查用户类型允许访问此操作,如果没有,我将他重定向到其他地方(在我的情况下,重定向到主仪表板页面).

    yes this is what i mean. I did similar thing on one of the systems that i developed, and i added one more guard so all the "logged in" routes pass in (like auth) and there i'm checking the requested rout and action and check if the user type is allow to access this action, and if not i redirected him to somewhere else (in my case to main dashboard page).

  • 添加新的中间件

    php artisan make:middleware Permissions
    

    在app \ Http \ Kernel.php中,添加到受保护的$ routeMiddleware新中间件

    in app\Http\Kernel.php, add to protected $routeMiddleware new middleware

    'permissions' => \App\Http\Middleware\Permissions::class,
    

    在路线"网站中添加登录所需的溃败并添加中间件权限...请注意 as 定义

    in Routes web add the desire routs for logged in and add the middleware permissions ... pay attention to the as definition

    Route::group(['middleware'=>['auth', 'permissions']], function() {
            // any of your routs ... for example
    
            Route::get('/', [
                'uses'=>"UserController@getUsers",
                'as'=>"users"
            ]);
    
            Route::get('/{id}', [
                'uses'=>"UserController@getUserEdit",
                'as'=>"users.edit"
            ]);
    });
    

    在新的中间件应用程序\ Http \ Middleware \ Permissions.php中, 调整公共功能句柄,并在其中添加用户级逻辑...请注意,对于切换情况,请检查 as ...与相同在routs网络文件中定义.

    in the new middleware app\Http\Middleware\Permissions.php, adjust the public function handle and add there the users level logic... pay attention that for the switch case checking the as ... the same as that defined in the routs web file.

    根据需要,为登录用户类型"添加更多检查...系统中的管理员,支持...等.

    add more check as you need for the logged in user "type"... Admin, Support ... and so on as you have in the system.

    public function handle($request, Closure $next, $guard = null)
    {
        $user = $request->user();
        $actions = $request->route()->getAction();
    
        switch( $actions['as'] ) {
            case "users":
                if( ! $user->isAdmin() ) {
                    //return redirect()->route("dashboard");
                }
            break;
    
            case "users.edit":
                if( ! $user->isAdmin() ) {
    
                }
            break;
    
            // add more cases as you need and check the user "type"
    
            default:
    
            break;
        }
    
        return $next($request);
    }
    

    如果您有很多溃败...那么也许最好添加一些小"中间件,并为每个路由组/前缀添加一个...检查用户是否允许访问此前缀. 例如...添加SupportMiddleware/SalesMiddleware ...,然后在其中的每一个中,您只需检查用户类型以及它是否适合当前的路线组即可.

    if you have a lot of routs... so maybe it will be better to add few "little" middleware and for every route group / prefix ... check if user allow to access this prefix. for example... add SupportMiddleware / SalesMiddleware ... and in every one of them you can just check the user type and if it's fit to the current group of routes.

    这篇关于Laravel Multi Auth-管理员防护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆