erjanmx / laravel-api-auth
简单易用的Laravel API授权中间件
v1.0.1
2018-06-05 13:00 UTC
Requires (Dev)
- mockery/mockery: 0.9.*
- phpunit/phpunit: ~5.0
This package is auto-updated.
Last update: 2024-09-08 22:39:15 UTC
README
Laravel Api Auth
Laravel提供了一种简单的方法来处理基于用户的API授权令牌,但有时您需要使用单个令牌来访问您的应用程序,尤其是在您正在开发需要相互连接的两个应用程序时,或者您可能需要使用webhooks将Telegram-bot连接到您的应用程序端点。
Laravel-api-auth使这变得非常容易,无需迁移,无需模型
安装包
如果您使用的是Laravel 5.5之前的版本,请考虑使用v0.1分支
$ composer require erjanmx/laravel-api-auth
发布包配置
$ php artisan vendor:publish --provider="Apiauth\Laravel\CAuthServiceProvider"
使用包
步骤1
在config/apiauth.php
中更改默认设置
<?php return [ 'services' => [ 'MY_APP' => [ // this is the name of the middleware of route group to be protected 'tokenName' => 'api_token', // name of key that will be checked for secret value 'token' => env('MY_APP_TOKEN'), // secret value that is retrieved from env vars and needs to be passed in requests in order to get access to your protected urls 'allowJsonToken' => true, 'allowBearerToken' => true, 'allowRequestToken' => true, ] ], ];
步骤2
- 在
.env
文件中添加您的密钥值
// .env
...your other variables
MY_APP_TOKEN=my-secret
步骤3
- 在路由文件中添加带有中间件的组
Route::group(['prefix' => 'api', 'middleware' => ['apiauth:MY_APP']], function () { // note the `MY_APP` that should match the name in your config we changed above Route::any('/', function () { return 'Welcome!'; }); });
这就完成了
您组内的URL只有在提供有效令牌的情况下才可访问
- 在
GET
或POST
请求中
- 在请求头中作为
Authorization Bearer
(在这种情况下忽略tokenName
)
- 在
json
原始体中
您还可以更改配置文件中的令牌名称(默认为api_token
)以及要检查的授权方法。您还可以设置任意数量的服务。