多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
闭包请求看守器 实现基于 HTTP 请求的自定义身份验证系统的最简单方法是使用 Auth::viaRequest 方法。此方法允许你使用单个闭包快速定义身份验证过程。 首先,请在 AuthServiceProvider 的 boot 方法中调用 Auth::viaRequest 方法。 VIASRequest 方法接受身份验证驱动程序名称作为其第一个参数。此名称可以是描述你的自定义看守器的任何字符串。传递给方法的第二个参数应该是一个闭包,该闭包接收传入的 HTTP 请求并返回用户实例,或者,如果身份验证失败返回 null: ~~~ <?php namespace App\Providers; use App\Models\MemberList; use DragonCode\Support\Facades\Helpers\Str; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class AuthServiceProvider extends ServiceProvider { /** * The model to policy mappings for the application. * * @var array<class-string, class-string> */ protected $policies = [ // ]; /** * Register any authentication / authorization services. */ public function boot(): void{ Auth::viaRequest('token', function (Request $request) { //客户端发送的token if (!$request->hasHeader('Authorization') || empty($request->header('Authorization'))){ return null; }/*end if*/ $decoder = api_token_decoder(trim($request->header('Authorization'))); if (empty($decoder)){ return null; } if (!preg_match("/^([1|2]\d{6,8})(_)(\d{1,3})$/",$decoder, $decoder_array)){ return null; }/*end if*/ if (!isset($decoder_array[1]) || !isset($decoder_array[3]) || !is_numeric($decoder_array[1])){ return null; }/*end if*/ $user_id = (int) $decoder_array[1]; /*用户ID*/ $encrypt = $decoder_array[3]; /*用户在线密钥*/ $member_info = MemberList::find($user_id); if (empty($member_info)){ return null; }/*end if*/ if ($member_info->encrypt != $encrypt){ return null; }/*end if*/ return $member_info; }); } } ~~~ 定义自定义身份验证驱动程序后,你可以将其配置为`auth.php`配置文件的`guards`配置中的驱动程序: ~~~ 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ], ~~~ ### 报错状态 ~~~ <?php namespace App\Http\Middleware; use App\Exceptions\ApiException; use Illuminate\Auth\Middleware\Authenticate as Middleware; use Illuminate\Http\Request; class Authenticate extends Middleware { /** * Get the path the user should be redirected to when they are not authenticated. */ protected function redirectTo(Request $request): ?string{ if ($request->expectsJson()){ throw new ApiException('سېستىمىغا كىرىپ ئاندىن مەشغۇلات قىلىڭ!', 401); } abort(404); } protected function unauthenticated($request, array $guards) { $this->redirectTo($request); } } ~~~ ~~~ /*************************************************** 以下需要token *******************************************************************/ Route::middleware(['auth:api'])->group(function (){ } ~~~