【问题标题】:Laravel: How to authenticate users without DBLaravel:如何在没有数据库的情况下对用户进行身份验证
【发布时间】:2018-11-09 03:53:38
【问题描述】:

正如标题所暗示的,是否可以在没有 DB 的情况下进行身份验证(而不是使用 User Provider)?

我看过关于如何在没有密码的情况下进行身份验证的帖子,但是是否有可能在没有DB的情况下进行身份验证?

这是我一直在努力实现的目标......

  1. 要求用户提交 PIN 码
  2. 将 PIN 与 .env 中的值进行比较
  3. 如果 PIN 正确,则对用户进行身份验证

introducing a user provider. 似乎可以在没有传统 RDBMS 的情况下进行身份验证

但是,该文档似乎没有描述用户提供程序的外观。

这是我的代码的 sn-ps(好吧,我只是模仿文档)...

class AuthServiceProvider extends ServiceProvider {

    public function boot()
    {
        $this->registerPolicies();

        Auth::provider('myUser', function ($app, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\UserProvider...

            return new MyUserProvider($app->make('myUser'));
        });
    }
}

auth.php...

'providers' => [
    'users' => [
        'driver' => 'myUser',
    ],
],

现在,我不知道如何继续。

所以,我想知道...

  1. user provider 应该是什么样子的

  2. 如果可以首先使用env() 对用户进行身份验证

我们将不胜感激。

【问题讨论】:

标签: php laravel laravel-5 laravel-5.6


【解决方案1】:

如果你知道用户是谁(IE:已经有一个 $user 实例),你可以简单地登录而不使用文档中显示的任何保护

Auth::login($user);

我会将用户实例而不是 $email/$password 传递给您的函数

$user = User::whereEmail($email)->first();
$class->login($user);

然后在你的课堂上

public static function Login(User $user) 
{
// ...
 if(substr ( $result, 0, 3 ) == '+OK')
    Auth::login($user);
    return true; //user will be logged in and then redirect
 else
    return false;
 }

【讨论】:

  • 感谢您的建议...但我处于 DB 不可用的情况。所以,User::whereEmail 不会得到任何实例。另外,我不认为可以使用Auth::login($user),因为我没有任何用户实例。
  • 也许这个答案不是最适合这个问题的,但是谷歌把我带到了这里,这就是我想要的:)
  • 答案提供了一些信息。如果有工作样本就好了。有没有可用的?
【解决方案2】:

谢谢大家,但是有一个更简单的解决方案……那就是使用session()

在控制器中,

public function login(Request $request)
{
    if ($request->input('pin') === env('PIN')) {
        $request->session()->put('authenticated', time());
        return redirect()->intended('success');
    }

    return view('auth.login', [
        'message' => 'Provided PIN is invalid. ',
    ]);
    //Or, you can throw an exception here.
}

路线的样子,

Route::group(['middleware' => ['web', 'custom_auth']], function () {
    Route::get('/success', 'Controller@success')->name('success');
});

custom_auth 看起来像,

public function handle($request, Closure $next)
{
    if (!empty(session('authenticated'))) {
        $request->session()->put('authenticated', time());
        return $next($request);
    }

    return redirect('/login');
}

希望这会对某人有所帮助。

【讨论】:

  • custom_auth 的位置是什么?您是否创建了一个简单的<form>,用户只需在其中输入 PIN 码即可?
  • 请考虑不要在您的控制器或模型中使用env()。您应该在config/ 目录中创建新的配置文件。如果您使用env(),缓存配置后您将获得null 值。 Docs
  • 每个用户都有相同的密码?还是只有一个用户? BC 将只有一个引脚将env 变量设置为 PIN。我错过了什么吗?这是不可能的......
【解决方案3】:

创建您自己的Guard 忽略UserProvider 接口。我在我的项目中采用了它,它运行良好。

PinGuard.php

<?php

declare(strict_types=1);

namespace App\Auth\Guards;

use App\User;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;

/**
 * Class PinGuard
 */
class PinGuard implements Guard
{
    /**
     * @var null|Authenticatable|User
     */
    protected $user;

    /**
     * @var Request
     */
    protected $request;

    /**
     * OpenAPIGuard constructor.
     *
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Check whether user is logged in.
     *
     * @return bool
     */
    public function check(): bool
    {
        return (bool)$this->user();
    }

    /**
     * Check whether user is not logged in.
     *
     * @return bool
     */
    public function guest(): bool
    {
        return !$this->check();
    }

    /**
     * Return user id or null.
     *
     * @return null|int
     */
    public function id(): ?int
    {
        $user = $this->user();
        return $user->id ?? null;
    }

    /**
     * Manually set user as logged in.
     * 
     * @param  null|\App\User|\Illuminate\Contracts\Auth\Authenticatable $user
     * @return $this
     */
    public function setUser(?Authenticatable $user): self
    {
        $this->user = $user;
        return $this;
    }

    /**
     * @param  array $credentials
     * @return bool
     */
    public function validate(array $credentials = []): bool
    {
        throw new \BadMethodCallException('Unexpected method call');
    }

    /**
     * Return user or throw AuthenticationException.
     *
     * @throws AuthenticationException
     * @return \App\User
     */
    public function authenticate(): User
    {
        $user = $this->user();
        if ($user instanceof User) {
            return $user;
        }
        throw new AuthenticationException();
    }

    /**
     * Return cached user or newly authenticate user.
     *
     * @return null|\App\User|\Illuminate\Contracts\Auth\Authenticatable
     */
    public function user(): ?User
    {
        return $this->user ?: $this->signInWithPin();
    }

    /**
     * Sign in using requested PIN.
     *
     * @return null|User
     */
    protected function signInWithPin(): ?User
    {
        // Implement your logic here
        // Return User on success, or return null on failure
    }

    /**
     * Logout user.
     */
    public function logout(): void
    {
        if ($this->user) {
            $this->setUser(null);
        }
    }
}

NoRememberTokenAuthenticatable.php

User 应该混入这个特征。

<?php

declare(strict_types=1);

namespace App\Auth;

use Illuminate\Database\Eloquent\Model;

/**
 * Trait NoRememberTokenAuthenticatable
 *
 * @mixin Model
 */
trait NoRememberTokenAuthenticatable
{
    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName()
    {
        return 'id';
    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->id;
    }

    /**
     * Get the password for the user.
     *
     * @return string
     * @codeCoverageIgnore
     */
    public function getAuthPassword()
    {
        throw new \BadMethodCallException('Unexpected method call');
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     * @codeCoverageIgnore
     */
    public function getRememberToken()
    {
        throw new \BadMethodCallException('Unexpected method call');
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param string $value
     * @codeCoverageIgnore
     */
    public function setRememberToken($value)
    {
        throw new \BadMethodCallException('Unexpected method call');
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     * @codeCoverageIgnore
     */
    public function getRememberTokenName()
    {
        throw new \BadMethodCallException('Unexpected method call');
    }
}

AuthServiceProvider.php

<?php

declare(strict_types=1);

namespace App\Providers;

use App\Auth\Guards\PinGuard;
use Illuminate\Container\Container;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [];

    /**
     * Register any authentication / authorization services.
     */
    public function boot()
    {
        Auth::extend('pin', function (Container $app) {
            return new PinGuard($app['request']);
        });
        $this->registerPolicies();
    }
}

config/auth.php

你应该注释掉其中的大部分。

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    // 'passwords' => [
    //     'users' => [
    //         'provider' => 'users',
    //         'table' => 'password_resets',
    //         'expire' => 60,
    //     ],
    // ],

];

【讨论】:

  • 那么就可以正常使用Auth Facade了,比如Auth::user()Auth::id()
  • 应该是答案
  • 使用这个解决方案,没有db的正常登录会是什么样子?请帮忙:stackoverflow.com/questions/60298133/…
  • 您能否展示一个代码示例来说明如何使用这个新的守卫。我将其用作登录请求。但仍然没有通过 auth 中间件: $user = new User([ 'id' => $result->success->user->id, 'name' => $result->success->user->name, ' email' => $result->success->user->email, 'password' => $password ]);验证::setUser($user); $re = Auth::authenticate();
猜你喜欢
  • 2018-10-26
  • 1970-01-01
  • 2016-08-02
  • 2021-11-16
  • 2022-06-10
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多