laravel 在laravel 5 中对来自两个以上表的用户进行身份验证

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

Authenticate users from more than two tables in laravel 5

phplaravelauthenticationlaravel-5.2

提问by RAUSHAN KUMAR

As I know Auth::attemptis used to authenticate users from userstable, but i want to authenticate another users from managerstable and admin from adminstable. I know there are laravel-multiauthplugin already exist. But can we create our own AuthServiceProviderfor authenticating users from multiple tables..?

据我所知Auth::attempt,用于对users表中的用户进行身份验证,但我想对managers表中的其他用户和表中的管理员进行身份验证admins。我知道laravel-multiauth插件已经存在。但是我们可以创建我们自己的AuthServiceProvider来验证来自多个表的用户吗?

采纳答案by Shams Reza

First create Admin Authenticatable in Illuminate\Foundation\Authlike

首先创建 Admin Authenticatable in Illuminate\Foundation\Authlike

    <?php

namespace Illuminate\Foundation\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

    class Admin extends Model implements
        AuthenticatableContract,
        AuthorizableContract,
        CanResetPasswordContract
    {
        use Authenticatable, Authorizable, CanResetPassword;
    }

Then create Admin Model by extending AuthenticatableAdmin Model :-

然后通过扩展Authenticatable管理模型来创建管理 模型:-

  <?php
namespace App;
use Illuminate\Foundation\Auth\Admin as Authenticatable;

class Admin extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

After that you need to modify config/auth.phplike below Add in providersarray

之后,您需要config/auth.php像下面这样修改Add in providers数组

'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ], 

and Add in guardsarray.

并添加警卫数组。

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

Now to authenticate from usertable

现在从用户表进行身份验证

 if (Auth::guard('user')->attempt(['email' => $email, 'password' => $password])) {
        $details = Auth::guard('user')->user();
        $user = $details['original'];
        return $user;
    } else {
        return 'auth fail';
    }

And to authenticate from Admintable

并从管理表进行身份验证

 if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password])) {
        $details = Auth::guard('admin')->user();
        $user = $details['original'];
        return $user;
    } else {
        return 'auth fail';
    }

回答by achillesp

You could setup multiple authentication guards, with each one having a different provider. The providers define the table or model to be used.

您可以设置多个身份验证防护,每个防护都有不同的提供者。提供者定义要使用的表或模型。

In config/auth.phpyou setup the providersas follows and you also setup corresponding guardsfor each of those providers:

config/auth.php您进行providers如下设置时,您还guards为每个提供者设置了相应的内容:

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

Then you can authenticate like this:

然后你可以像这样进行身份验证:

Auth::attempt($credentials) // use default guard for simple users
Auth::guard('manager')->attempt($credentials)
Auth::guard('admin')->attempt($credentials)

Check out the docs here.

此处查看文档。

回答by Jonjie

Try my idea if you want to. I'm expecting that different tablehas different users. Because it won't work if you have the same userin other tables.

如果你愿意,试试我的想法。我期待不同的table有不同的users. 因为如果您user在其他表中具有相同的内容,它将不起作用。

  1. Choose your priority table (e.g. users)
  2. Add the condition
    • if(Auth::user(attempt(...))
    • elseif(Auth::manager(attempt(...))
    • elseif(Auth::admins(attempt(...)))
  1. 选择您的优先级表(例如用户)
  2. 添加条件
    • if(Auth::user(attempt(...))
    • elseif(Auth::manager(attempt(...))
    • elseif(Auth::admins(attempt(...)))

Note: Your priority table here is users, then if the user doesn't exists in that table, it will try the managerstable, then if still doesn't exists, it will check the adminstable, otherwise (use else) return a message error.

注意:你这里的优先级表是users,那么如果该表中不存在用户,它会尝试该managers表,如果仍然不存在,它会检查该admins表,否则(使用else)返回消息错误。

Other option:

其他选择:

Other option is to use this package sarav/laravel-multiauth. You can follow this thread. How to use authentication for multiple tables in Laravel 5for more information.

另一个选择是使用这个包sarav/laravel-multiauth。你可以关注这个线程。如何在 Laravel 5 中多个表使用身份验证以获取更多信息。

More Reference:

更多参考:

https://laracasts.com/discuss/channels/general-discussion/using-laravel-auth-for-multiple-tables?page=1

https://laracasts.com/discuss/channels/general-discussion/using-laravel-auth-for-multiple-tables?page=1

Can anyone explain Laravel 5.2 Multi Auth with example

谁能用例子解释 Laravel 5.2 Multi Auth

https://laracasts.com/discuss/channels/laravel/52-auth-multiple-tables?page=1

https://laracasts.com/discuss/channels/laravel/52-auth-multiple-tables?page=1

回答by Sanzeeb Aryal

Create a model for managers table and admins table. This model should extend Illuminate\Foundation\Auth\User

为 manager 表和 admins 表创建模型。这个模型应该扩展Illuminate\Foundation\Auth\User

In config/auth.php,

config/auth.php,

Add to the providers array:

添加到提供者数组:

'managers' => [
    'driver' => 'eloquent',
    'model' => App\Manager::class,
 ],

Add to the guards array:

添加到守卫数组:

'web_manager' => [
    'driver' => 'session',
    'provider' => 'managers',
 ],

Then. in LoginController(create one for manager using php artisan make:auth) use the trait Illuminate\Foundation\Auth\AuthenticatesUsersand override guard and redirect properties.

然后。在LoginController(为 manager using 创建一个php artisan make:auth)使用 traitIlluminate\Foundation\Auth\AuthenticatesUsers并覆盖守卫和重定向属性。

protected $redirectTo = 'redirect_path_after_manager_login';

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

The manager model is authenticated and you can get the auuthenticated manager's object Auth::guard('web_manager')->user();

管理器模型已通过身份验证,您可以获得经过身份验证的管理器对象 Auth::guard('web_manager')->user();