kiriunin/api-guard
Composer 安装命令:
composer require kiriunin/api-guard
包简介
A simple way of authenticating your APIs with API keys using Laravel
README 文档
README
A simple way of authenticating your APIs with API keys using Laravel. This package uses the following libraries:
- philsturgeon's Fractal
- maximebeaudoin's api-response
Laravel 5.3, 5.4 and 5.5 is finally supported!
**Laravel 5.3.x onwards: ~4.*
**Laravel 5.1.x to 5.2.x: ~3.*
**Laravel 5.1.x: ~2.*
**Laravel 4.2.x: ~1.* (Recently updated version for Laravel 4. Please note that there are namespace changes here)
**Laravel 4.2.x: 0.* (The version that most of you are using)
Quick start
Installation for Laravel 5.3 to 5.4
Run composer require chrisbjr/api-guard 4.*
In your config/app.php add Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider to the end of the providers array
'providers' => array( ... Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider::class, ),
Now publish the migration and configuration files for api-guard:
$ php artisan vendor:publish --provider="Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider"
Then run the migration:
$ php artisan migrate
It will setup api_keys table.
Generating your first API key
Once you're done with the required setup, you can now generate your first API key.
Run the following command to generate an API key:
php artisan api-key:generate
Generally, the ApiKey object is a polymorphic object meaning this can belong to more than one other model.
To generate an API key that is linked to another object (a "user", for example), you can do the following:
+php artisan api-key:generate --id=1 --type="App\User"
To specify that a model can have API keys, you can attach the Apikeyable trait to the model:
use Chrisbjr\ApiGuard\Models\Mixins\Apikeyable; class User extends Model { use Apikeyable; ... }
This will attach the following methods to the model:
// Get the API keys of the object $user->apiKeys(); // Create an API key for the object $user->createApiKey();
To generate an API key from within your application, you can use the following method in the ApiKey model:
$apiKey = Chrisbjr\ApiGuard\Models\ApiKey::make() // Attach a model to the API key $apiKey = Chrisbjr\ApiGuard\Models\ApiKey::make($model)
Usage
You can start using ApiGuard by simply attaching the auth.apikey middleware to your API route:
Route::middleware(['auth.apikey'])->get('/test', function (Request $request) { return $request->user(); // Returns the associated model to the API key });
This effectively secures your API with an API key which needs to specified in the X-Authorization header. This can be configured in config/apiguard.php.
Here is a sample cURL command to demonstrate:
curl -X GET \
http://apiguard.dev/api/test \
-H 'x-authorization: api-key-here'
You might also want to attach this middleware to your api middleware group in your app/Http/Kernel.php to take advantage of other Laravel features such as
throttling.
/** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ ... 'api' => [ 'throttle:60,1', 'bindings', 'auth.apikey', ], ];
If you noticed in the basic example, you can also access the attached model to the API key by calling $request->user(). We are attaching the related model in
this method because in most use cases, this is actually the user.
Unauthorized Requests
Unauthorized requests will get a 401 status response with the following JSON:
{
"error": {
"code": "401",
"http_code": "GEN-UNAUTHORIZED",
"message": "Unauthorized."
}
}
ApiGuardController
The ApiGuardController takes advantage of Fractal and api-response libraries.
This enables us to easily create APIs with models and use transformers to give a standardized JSON response.
Here is an example:
Let's say you have the following model:
use Illuminate\Database\Eloquent\Model; class Book extends Model { protected $fillable = [ 'name', ]; }
You can make a basic controller which will return all books like this:
use Chrisbjr\ApiGuard\Http\Controllers\ApiGuardController; use App\Transformers\BookTransformer; use App\Book; class BooksController extends ApiGuardController { public function all() { $books = Book::all(); return $this->response->withCollection($books, new BookTransformer); } }
Now, you'll need to make the transformer for your Book object. Transformers help with defining and manipulating the variables you want to return to your JSON response.
use League\Fractal\TransformerAbstract; use App\Book; class BookTransformer extends TransformerAbstract { public function transform(Book $book) { return [ 'id' => $book->id, 'name' => $book->name, 'created_at' => $book->created_at, 'updated_at' => $book->updated_at, ]; } }
Once you have this accessible in your routes, you will get the following response from the controller:
{
"data": {
"id": 1,
"title": "The Great Adventures of Chris",
"created_at": {
"date": "2017-05-25 18:54:18",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2017-05-25 18:54:18",
"timezone_type": 3,
"timezone": "UTC"
}
}
}
More examples can be found on the Github page: https://github.com/ellipsesynergie/api-response.
To learn more about transformers, visit the PHP League's documentation on Fractal: Fractal
API Validation Responses
ApiGuard comes with a request class that can handle validation of requests for you and throw a standard response.
You can create a Request class as you usually do but in order to get a standard JSON response you'll have to extend the ApiGuardFormRequest class.
use Chrisbjr\ApiGuard\Http\Requests\ApiGuardFormRequest; class BookStoreRequest extends ApiGuardFormRequest { public function authorize() { return true; } public function rules() { return [ 'name' => 'required', ]; } }
Now you can use this in your controller as you normally do with Laravel:
use Chrisbjr\ApiGuard\Http\Controllers\ApiGuardController; use App\Transformers\BookTransformer; use App\Book; class BooksController extends ApiGuardController { public function store(BookStoreRequest $request) { // Request should already be validated $book = Book::create($request->all()) return $this->response->withItem($book, new BookTransformer); } }
If the request failed to pass the validation rules, it will return with a response like the following:
{
"error": {
"code": "GEN-UNPROCESSABLE",
"http_code": 422,
"message": {
"name": [
"The name field is required."
]
}
}
}
kiriunin/api-guard 适用场景与选型建议
kiriunin/api-guard 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 21 次下载、GitHub Stars 达 0, 最近一次更新时间为 2019 年 11 月 12 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「json」 「rest」 「api」 「laravel」 「api keys」 「api authentication」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 kiriunin/api-guard 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 kiriunin/api-guard 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 kiriunin/api-guard 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Kinikit - PHP Application development framework MVC component
ext-json wrapper with sane defaults
A package to cast json fields, each sub-keys is castable
A PSR-7 compatible library for making CRUD API endpoints
Api bundle
swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations
统计信息
- 总下载量: 21
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 6
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: Unknown
- 更新时间: 2019-11-12