api-skeletons/laravel-doctrine-apikey
Composer 安装命令:
composer require api-skeletons/laravel-doctrine-apikey
包简介
API keys with scopes for Laravel Doctrine
README 文档
README
This repository provides a driver for Doctrine which can be added to an existing entity manager.
The driver provides a set of entities which enable ApiKey authorization through HTTP middleware.
Scopes are supported! This was the missing piece of other repositories which catalyzed the creation of this library.
Installation
Run the following to install this library using Composer:
composer require api-skeletons/laravel-doctrine-apikey
Quick Start
Add Service Provider to app.php
'providers' => [ ... ApiSkeletons\Laravel\Doctrine\ApiKey\ServiceProvider::class, ],
Add the route middleware to Http Kernel
use ApiSkeletons\Laravel\Doctrine\ApiKey\Http\Middleware\AuthorizeApiKey; $routeMiddleware = [ ... 'auth.apikey' => AuthorizeApiKey:class ];
Initialize the ApiKey service for your entity manager in App\Providers\AppServiceProvider
use ApiSkeletons\Laravel\Doctrine\ApiKey\Service\ApiKeyService; public function boot() { app(ApiKeyService::class)->init(app('em')); }
Add an API key through the console
$ php artisan apikey:generate yourapikeyname
Add the middleware to a protected route
Route::name('api.resource::fetch') ->get('resource', 'ResourceController::fetch') ->middleware('auth.apikey');
Begin making requests to your ApiKey protected resource using your apikey as a Bearer token in the Authorization header
Authorization: Bearer {apikey}
Schema
Using Scopes
Scopes are permissions for ApiKeys. They are commonly used in OAuth2 and are less common in ApiKeys. Create a scope:
php artisan apikey:scope:generate {name}
Security with scopes is applied with the same middleware used to authenticate ApiKeys. Replace {scopeName} with your scope's name and the middleware will ensure the passed ApiKey has that scope to continue.
Route::name('api.resource::fetch') ->get('resource', 'ResourceController::fetch') ->middleware('auth.apikey:{scopeName}');
Access to ApiKey through request attributes
The ApiKey entity which authenticates a request is assigned to the request attributes as 'apikey'.
$apiKey = request()->attributes->get('apikey');
Using foreign keys to ApiKey
Because an ApiKey can be regenerated, there may be no reason to assign multiple API keys to the same entity. For instance, if each Customer has a 1:1 with ApiKey then you can safely disable that key, regenerate it, and so on; never needing to assign a new ApiKey.
To dynamically create a 1:1 relationship between a Customer entity and API key, create an event subscriber:
<?php declare(strict_types=1); namespace App\ORM\Event\Subscriber; use ApiSkeletons\Laravel\Doctrine\ApiKey\Entity\ApiKey; use App\ORM\Entity\Customer; use Doctrine\Common\EventSubscriber; use Doctrine\ORM\Event\LoadClassMetadataEventArgs; use Doctrine\ORM\Events; class ApiKeyEventSubscriber implements EventSubscriber { /** * {@inheritDoc} */ public function getSubscribedEvents() { return [ Events::loadClassMetadata, ]; } public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void { // the $metadata is the whole mapping info for this class $metadata = $eventArgs->getClassMetadata(); switch ($metadata->getName()) { case Customer::class: $metadata->mapOneToOne([ 'targetEntity' => ApiKey::class, 'fieldName' => 'apiKey', ]); break; default: break; } } }
Event Logging
Admin events are logged when an ApiKey is generated, activated, deactivated, add a scope, and remove a scope.
Access events are logged when the route middleware allows access to a resource.
Commands
Management of API keys is handled through the command line. However, full access to all data-creating functions is available through the Doctrine repositories: ApiKeyRepository and ScopeRepository.
Generate an ApiKey
php artisan apikey:generate {name}
Generate a Scope
php artisan apikey:scope:generate {name}
Assign a Scope to an ApiKey
php artisan apikey:scope:add {apiKeyName} {scopeName}
Deactivate an ApiKey
php artisan apikey:deactivate {name}
Activate an ApiKey
php artisan apikey:activate {name}
Unassign a Scope from an ApiKey
php artisan apikey:scope:remove {apiKeyName} {scopeName}
Regenerate an ApiKey (assign a new Bearer token)
php artisan apikey:regenerate {name}
Delete a Scope
php artisan apikey:scope:delete {scopeName}
Print ApiKey[s]
php artisan apikey:print {name?}
Print Scope[s]
php artisan apikey:scope:print {name?}
Multiple object managers
The metadata included with this repository works fine across multiple object managers.
The commands included in this repository only work on the default ApiKeyService, so you will need an alternative
method of maintaining data in the second object manager. In order
to use multiple object managers you must do some configuration. Assuming you followed the Quick Start, above,
follow these steps for a second object manager:
Create a new singleton of the ApiKeyService with a different name in App\Providers\AppServiceProvider
use ApiSkeletons\Laravel\Doctrine\ApiKey\Service\ApiKeyService; public function register(): void { $this->app->singleton('ApiKeyService2', static function ($app) { return new ApiKeyService(); }); }
Initialize the ApiKey service for the second entity manager in App\Providers\AppServiceProvider
public function boot() { app('ApiKeyService2')->init(app('em2')); }
Copy the route middleware to a new class and use dependency injection for the ApiKeyService2
$routeMiddleware = [ ... 'auth.apikey2' => EditedAuthorizeApiKey:class ];
Inspired By
The repository https://github.com/ejarnutowski/laravel-api-key was the inispiration for this repository. It seemed a fine project but did not have unit tests or scopes.
api-skeletons/laravel-doctrine-apikey 适用场景与选型建议
api-skeletons/laravel-doctrine-apikey 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 7.49k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 12 月 17 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 api-skeletons/laravel-doctrine-apikey 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 api-skeletons/laravel-doctrine-apikey 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 7.49k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 13
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-12-17
