用户登录
用户注册

分享至

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

  • 作者: BETTER62881837
  • 来源: 51数据库
  • 2022-10-21

问题描述

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

As I know Auth::attempt is used to authenticate users from users table, but i want to authenticate another users from managers table and ***** from *****s table. I know there are laravel-multiauth plugin already exist. But can we create our own AuthServiceProvider for authenticating users from multiple tables..?

推荐答案

首先在 IlluminateFoundationAuth 中创建 ***** Authenticatable 就像

First create ***** Authenticatable in IlluminateFoundationAuth like

    <?php

namespace IlluminateFoundationAuth;
use IlluminateAuthAuthenticatable;
use IlluminateDatabaseEloquentModel;
use IlluminateAuthPasswordsCanResetPassword;
use IlluminateFoundationAuthAccessAuthorizable;
use IlluminateContractsAuthAuthenticatable as AuthenticatableContract;
use IlluminateContractsAuthAccessAuthorizable as AuthorizableContract;
use IlluminateContractsAuthCanResetPassword as CanResetPasswordContract;

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

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

Then create ***** Model by extending Authenticatable ***** Model :-

  <?php
namespace App;
use IlluminateFoundationAuth***** as Authenticatable;

class ***** 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',
    ];
}

之后你需要像下面这样修改config/auth.php添加提供者数组

After that you need to modify config/auth.php like below Add in providers array

'*****s' => [
            'driver' => 'eloquent',
            'model' => App*****::class,
        ], 

并加入guards数组.

 'user' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
 '*****' => [
            'driver' => 'session',
            'provider' => '*****s',
        ],

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

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

并从*****表进行身份验证

 if (Auth::guard('*****')->attempt(['email' => $email, 'password' => $password])) {
        $details = Auth::guard('*****')->user();
        $user = $details['original'];
        return $user;
    } else {
        return 'auth fail';
    }
软件
前端设计
程序设计
Java相关