moh_abk's avatar

Lumen authentication

I'm attempting to integrate some authentication into my Lumen API and reading through the documentation it seems that you need a DB and a User model as stated below;

Auth::viaRequest('api', function ($request) {
    // Return User or null...
});

But what if I just want to return true after performing a check of the API token?

This is a grab from AuthServiceProvider.php

Auth::viaRequest('api', function ($request) {
    if ($request->input('api_token')) {
        return User::where('api_token', $request->input('api_token'))->first();
    }
});

Here they are performing a DB query on the User model to determine if the api_token matches what the User has in their DB row.

How can I do something like this;

Auth::viaRequest('api', function ($request) {
    if ($request->input('api_token') == env('APP_KEY')) {
        // what should i return here?
    } else {
        return null;
    }
});

Also here they're checking a parameter passed with the request. How can I check the request header because that's how I'll be sending the api_token

0 likes
3 replies
juandmegon's avatar

I'm not sure if it is a good idea to use the APP_KEY to validate requests, basically once you get that value it still the same, at least that you change it every time, and the APP_KEY is going to be exposed as well.

I recommend you something more suitable like JWT or OAuth2:

JWT: https://goo.gl/XmbeYS

or OAuth2: https://goo.gl/Pyp5qQ

Check here some videos of OAuth2:

Hope it helps.

1 like
moh_abk's avatar

So based on the way they have it setup each request I send should have the api_token of the user sent with it correct? Then I just use the DB facade to check if it's correct

juandmegon's avatar

Yes, normally you have to sent an access_token (or api_token) to validate the request. It is mandatory to validate the request that the access_token comes from a valid user of the system.

In this way, if you prefeer to implement it by your own, you have to obtain the access_token and then found if there exists a user who own that access_token.

Take into account that the access_token shpuld be compromised in some way, so it is a good idea to have som time to be valid and a way to refresh the token.

Hope I was clear on it, let me know if you want to know something else.

Please or to participate in this conversation.