expanse / api-guard
使用Laravel通过API密钥简单验证您的API
Requires
- php: ^7.2
- ellipsesynergie/api-response: *
- illuminate/database: ^5.3.0 || ^6.0
- illuminate/support: ^5.3.0 || ^6.0
Requires (Dev)
- phpunit/phpunit: ^4.0 || ^5.0 || ^8.0
This package is auto-updated.
Last update: 2024-09-29 05:43:00 UTC
README
使用Laravel通过API密钥简单验证您的API。此包使用以下库
- philsturgeon的Fractal
- maximebeaudoin的api-response
Laravel 5.3、5.4和5.5终于支持了!
**从Laravel 5.3.x开始:~4.*
**Laravel 5.1.x到5.2.x:~3.*
**Laravel 5.1.x:~2.*
**Laravel 4.2.x:~1.*(为Laravel 4最近更新的版本。请注意,这里有一些命名空间更改)
**Laravel 4.2.x:0.*(你们大多数人在使用的版本)
快速开始
Laravel 5.3到5.4的安装
运行composer require chrisbjr/api-guard 4.*
在您的config/app.php中将Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider添加到providers数组的末尾
'providers' => array( ... Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider::class, ),
现在发布api-guard的迁移和配置文件
$ php artisan vendor:publish --provider="Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider"
然后运行迁移
$ php artisan migrate
这将设置api_keys表。
生成您的第一个API密钥
完成所需的设置后,您现在可以生成第一个API密钥。
运行以下命令生成API密钥
php artisan api-key:generate
通常,ApiKey对象是一个多态对象,这意味着它可以属于多个其他模型。
要生成与另一个对象(例如“用户”)关联的API密钥,您可以执行以下操作
+php artisan api-key:generate --id=1 --type="App\User"
要指定模型可以拥有API密钥,可以将Apikeyable特质附加到模型
use Chrisbjr\ApiGuard\Models\Mixins\Apikeyable; class User extends Model { use Apikeyable; ... }
这将向模型附加以下方法
// Get the API keys of the object $user->apiKeys(); // Create an API key for the object $user->createApiKey();
要从您的应用程序内部生成API密钥,您可以在ApiKey模型中使用以下方法
$apiKey = Chrisbjr\ApiGuard\Models\ApiKey::make() // Attach a model to the API key $apiKey = Chrisbjr\ApiGuard\Models\ApiKey::make($model)
用法
您可以通过将auth.apikey中间件附加到您的API路由来开始使用ApiGuard
Route::middleware(['auth.apikey'])->get('/test', function (Request $request) { return $request->user(); // Returns the associated model to the API key });
这实际上使用需要在X-Authorization头中指定的API密钥来保护您的API。这可以在config/apiguard.php中配置。
以下是一个示例cURL命令来展示
curl -X GET \
http://apiguard.dev/api/test \
-H 'x-authorization: api-key-here'
您还可能想将此中间件附加到您的api中间件组中的app/Http/Kernel.php,以利用Laravel的其他功能,例如限流。
/** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ ... 'api' => [ 'throttle:60,1', 'bindings', 'auth.apikey', ], ];
如果在基本示例中注意到,您还可以通过调用$request->user()来访问附加到API密钥的模型。我们在该方法中附加相关模型,因为在大多数情况下,这实际上是用户。
未授权请求
未授权请求将获得包含以下JSON的401状态响应
{
"error": {
"code": "401",
"http_code": "GEN-UNAUTHORIZED",
"message": "Unauthorized."
}
}
ApiGuardController
ApiGuardController利用Fractal和api-response库。
这使我们能够轻松创建具有模型和转换器的API,以提供标准化的JSON响应。
以下是一个示例
假设您有以下模型
use Illuminate\Database\Eloquent\Model; class Book extends Model { protected $fillable = [ 'name', ]; }
您可以使用基本控制器返回所有书籍,如下所示
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); } }
现在,您需要为您的 Book 对象创建一个转换器。转换器有助于定义和操作您想要返回到 JSON 响应中的变量。
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, ]; } }
一旦您在路由中访问到这个,您将从控制器获得以下响应
{
"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"
}
}
}
更多示例可以在 GitHub 页面上找到:https://github.com/ellipsesynergie/api-response。
要了解更多关于转换器的信息,请访问 PHP League 的 Fractal 文档:Fractal
API 验证响应
ApiGuard 包含一个请求类,它可以为您处理请求验证并抛出一个标准响应。
您可以像往常一样创建一个 Request 类,但要获取标准 JSON 响应,您必须扩展 ApiGuardFormRequest 类。
use Chrisbjr\ApiGuard\Http\Requests\ApiGuardFormRequest; class BookStoreRequest extends ApiGuardFormRequest { public function authorize() { return true; } public function rules() { return [ 'name' => 'required', ]; } }
现在您可以在控制器中使用它,就像您通常使用 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); } }
如果请求未通过验证规则,它将返回如下响应
{
"error": {
"code": "GEN-UNPROCESSABLE",
"http_code": 422,
"message": {
"name": [
"The name field is required."
]
}
}
}