mpyw/null-auth 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mpyw/null-auth

Composer 安装命令:

composer require mpyw/null-auth

包简介

Null Guard for Laravel. Designed for Middleware-based authentication and testing.

README 文档

README

Null Guard for Laravel. Designed for Middleware-based authentication and testing.

Requirements

  • PHP: ^8.2
  • Laravel: ^11.0 || ^12.0 || ^13.0

Note

Older versions have outdated dependency requirements. If you cannot prepare the latest environment, please refer to past releases.

Installing

composer require mpyw/null-auth

Features

NullAuthenticatable family

Trait ID Password Remember Token
GenericNullAuthenticatable
GenericStrictNullAuthenticatable
❗️
NullAuthenticatable
StrictNullAuthenticatable
NoRememberTokenAuthenticatable
StrictNoRememberTokenAuthenticatable
  • ❗️shows containing abstract methods.
  • Strict traits throw BadMethodCallException on bad method calls.

NullGuard

  • NullGuard::user() always returns Authenticatable already set by NullGuard::setUser().
  • NullGuard::unsetUser() can unset user.

NullUserProvider

  • All methods do nothing and always returns falsy value.

Usage

Basic Usage

Edit your config/auth.php.

<?php

return [

    /* ... */

    /*
    |--------------------------------------------------------------------------
    | 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' => 'null', // Use NullGuard for "web"
            'provider' => 'users',
        ],

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

    /*
    |--------------------------------------------------------------------------
    | 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' => 'null', // Use NullUserProvider for "users"
        ],
        
        // 'users' => [
        //     'driver' => 'eloquent',
        //     'model' => App\User::class,
        // ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /* ... */
];

Motivation

Guard-based API Authentication

Consider authentication that sends HTTP requests to the external platform.

In such a situation, you will probably use RequestGuard through Auth::viaRequest() call. However, some methods on the contracts UserProvider and Authenticatable are unsuitable for that. They heavily rely on the following flow:

  1. Retrieve a user from database by email address
  2. Verify user's password hash

This library provides a helper that makes the useless contract methods to do nothing; always return nullish or falsy values.

Now we include NullAuthenticatable trait on a user model.

<?php

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Mpyw\NullAuth\NullAuthenticatable;

class User extends Model implements Authenticatable
{
    use NullAuthenticatable;
}

Then only getAuthIdentifierName() and getAuthIdentifier() are provided as a valid implementation.

<?php

$user = User::find(1);

// Minimal implementation for Authenticatable
var_dump($user->getAuthIdentifierName()); // string(2) "id"
var_dump($user->getAuthIdentifier());     // int(1)

// Useless implementation for Authenticatable when we don't use StatefulGuard
var_dump($user->getAuthPassword());       // string(0) ""
var_dump($user->getRememberTokenName());  // string(0) ""
var_dump($user->getRememberToken());      // string(0) ""
$user->setRememberToken('...');           // Does nothing

Middleware-based Authentication

Suppose you hate using RequestGuard and wish implementing authentication on middleware.

Methods such as Auth::user() cause side effects when called for the first time on each request. This may lead to inappropriate behaviors if you concentrate authentication on middleware and use Auth::user() only as a container for Authenticatable object.

Don't worry. This library provides NullGuard, which is exactly as a simple Authenticatable container that you want. Auth::user() does nothing but returning the cached Authenticatable. You can just focus on calling Auth::setUser() on your cool middleware at ease.

<?php

namespace App\Http\Middleware;

use App\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Example\API\Authentication\Client;

class AuthenticateThroughExternalAPI
{
    /**
     * @var \Example\API\Authentication\Client
     */
    protected $client;

    /**
     * @param \Example\API\Authentication\Client $client
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Return user_id on success, throw AuthenticationException on failure
        $userId = $this->client->authenticate($request->input('token'));

        // Return User on success, throw ModelNotFoundException on failure
        $user = User::findOrFail($userId);

        Auth::setUser($user);

        return $next($request);
    }
}

Testing

Needless to say, it is also useful for testing. There is no worry about causing side effects.

mpyw/null-auth 适用场景与选型建议

mpyw/null-auth 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 113.83k 次下载、GitHub Stars 达 18, 最近一次更新时间为 2019 年 12 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「auth」 「laravel」 「illuminate」 「Dummy」 「null」 「none」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mpyw/null-auth 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mpyw/null-auth 我们能提供哪些服务?
定制开发 / 二次开发

基于 mpyw/null-auth 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 113.83k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 18
  • 点击次数: 28
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 18
  • Watchers: 1
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-12-09