Dead simple Laravel api auth middleware
Laravel gives easy ways to handle api authorization using user based tokens, but sometimes you need to use a single token to give access to your application, especially when you’re developing two apps that need to be connected, or perhaps you’re in need of connecting Telegram-bot to your app endpoint using webhooks
Laravel-api-auth makes that easy as breathe, no migrations, no models
If you’re using Laravel prior to 5.5, consider using v0.1 branch
$ composer require erjanmx/laravel-api-auth
Publish the Package configuration
$ php artisan vendor:publish --provider="Apiauth\Laravel\CAuthServiceProvider"
Change defaults in 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,
]
],
];
.env
file…your other variables
MY_APP_TOKEN=my-secret
#### Step 3
- Add group with middleware in your routes file
```php
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!';
});
});
Your urls within your group are accessible only if valid token provided
GET
or POST
requestAuthorization Bearer
(tokenName
is ignored in this case)json
raw bodyYou’re free to change token name (api_token
by default) in configuration file as well as
authorization methods to be checked.
Also you can set as many services as you want.