Reached's avatar

Protecting my API

Hi guys,

Im trying to build a small API with Lumen, and I want to protect it so that people from the outside cannot access it's data. At a later stage I also want to authorize each user, but for now it's only the API itself.

I watched Jeffreys tutorial here: https://laracasts.com/series/whats-new-in-laravel-5-2/episodes/5, but this is only for the individual users of the application.

I tried to build my own version of this, but I want to know if there is a better way to do this? It works, but it feels kinda wrong :P

routes.php

// Im passing in the api_key with each request
$app->group(['prefix' => 'api/{api_key}'], function () use ($app) {
    $app->get('/programmes', [
        'as' => 'allProgrammes',
        'uses' => 'App\Http\Controllers\ProgrammesController@index'
    ]);
});

ProgrammesController.php

public function index($api_key) {
       // If the API key matches, return the values
     if($api_key == env('API_KEY')) {
            $programmes = ['Full Body', 'Two Split', 'Three Split'];

            return $programmes;
    // Otherwise abort the program
        } else {
            abort(401);
        }
    }
0 likes
5 replies
fideloper's avatar

Is this an API used internally only then? (Not by application users directly?)

Reached's avatar

Hi @fideloper,

The API is meant to be consumed by a phone app that I plan to build, so I on that end I will check that it's using the correct key, and then if others are trying to access the API from the outside, they are not allowed to :)

Does that make sense?

Reached's avatar

Hi @jimmck,

I think I changed my mind about this, and will implement it with a token pr. user, since everything inside the app will have to be user based anyway.

How does using the above package work compared to using the method that Jeffrey describes in his video? I guess it's just a convenience layer, so that if I don't use the package, I would have to somehow store the token on the user myself in the application and send it along with each request to the api?

Please or to participate in this conversation.