thunken/api-guard

此包已被废弃且不再维护。未建议替代包。
此包的最新版本(5.0)没有可用的许可证信息。

使用Laravel通过API密钥验证您的API的简单方法

5.0 2020-01-22 10:59 UTC

README

使用Laravel通过API密钥验证您的API的简单方法。此包使用了以下库

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 6的安装

运行composer require thunken/api-guard 5.*

在您的config/app.php中,将Thunken\ApiGuard\Providers\ApiGuardServiceProvider添加到providers数组末尾

'providers' => array(

    ...
    Thunken\ApiGuard\Providers\ApiGuardServiceProvider::class,
),

现在发布api-guard的迁移和配置文件

$ php artisan vendor:publish --provider="Thunken\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 Thunken\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 = Thunken\ApiGuard\Models\ApiKey::make()

// Attach a model to the API key
$apiKey = Thunken\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
});

这实际上通过API密钥保护了您的API,该密钥需要指定在X-Authorization头部。这可以在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利用了Fractalapi-response库。

这使得我们能够轻松创建带有模型的API,并使用转换器来提供标准化的JSON响应。

以下是一个示例

假设您有以下模型

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable = [
        'name',
    ];
}

您可以创建一个基本的控制器,它会返回所有书籍,如下所示

use Thunken\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 Thunken\ApiGuard\Http\Requests\ApiGuardFormRequest;

class BookStoreRequest extends ApiGuardFormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required',
        ];
    }
}

现在您可以在控制器中使用它,就像您通常使用Laravel一样

use Thunken\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."
      ]
    }
  }
}