Reputation: 43
I'm new to the Laravel API world. I want to make a simple Laravel application than returns some stuff in json format. I don't want it to be accessible to anyone with the url link though. I want to allow the access only by one API key. Is it possible? Or every user must have a unique key? And how can it be done?
Upvotes: 2
Views: 8607
Reputation: 194
Yes, it is absolutely possible. We do not know your application requirements, however if you wish only to return some stuff and therefore you have no need for identifying which user did what, there is no reason to go with key per user as another answer suggested.
For example, you can put your key in .env
API_KEY=yourkey
And then, simply add middleware to api routes, which will first check, if there is a proper ApiKey passed within the request.
You can pass your env variable to any config file and then call config('yourConfigFile.apiKey')
anywhere in your app.
For some simple scenarios this approach is 100% sufficient. Take into consideration who will have access to this key and how it will be passed. If there will be one global key, and your api consumer will simply use ajax without proxing it via server, your api key will be exposed and everyone will be able to grab it and use it anywhere.
If that is the case, you can still avoid creating key per user – just specify list of allowed domains which can call your API and then check key. It all can be checked within middleware.
Like I said, know your requirements/use cases and then make a decision :-)
Upvotes: 3
Reputation: 2629
yes possible.
You have to have api_token field in users table and also add middleware in your api routes. api.php
Schema::table('users', function ($table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
middleware in api routes (api.php):
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
You can define custom api guards for your api as well, for example if you have two tables called doctor and patient, you will have two tables and for both users you will be need unique api_token, you can define those custom api guards in your config/auth.php
see here: https://laravel.com/docs/5.8/api-authentication
Upvotes: 5