2

In the AuthServiceProvider;

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

I can't seem to get this to work. GET requests do not have a body so no input is present. Also I've tried using $request->header('api_token') but still getting unauthorised

If I do an independent search on the DB like below it works;

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

Can anyone confirm that the $request header can be accessed here?

patricus
  • 59,488
  • 15
  • 143
  • 145
moh_abk
  • 2,064
  • 7
  • 36
  • 65
  • 1
    What does the request look? – tptcat Jan 10 '16 at 14:39
  • Input for `GET` requests comes from the query string: `http://example.com/users?api_token=my_api_key`. – patricus Jan 10 '16 at 21:27
  • Still doesn't work. I've tried it with `POST` as well and it works with `POST` because I put the `api_token` in the body. Also you should know that you don't have `?` in `laravel/lumen` so I just modified my route to `/{api_token}` – moh_abk Jan 10 '16 at 23:27
  • lumen knows how to handle variables passed in via the query string just fine. If you pass in the `api_token` as part of your query string, you can access it just fine with the `$request` variable. However, it looks like you got the header method working, so that is good, as well. – patricus Jan 11 '16 at 22:23

1 Answers1

0

Before you read my answer, please read this article (just in case you're using Apache Web Server).

Headers containing invalid characters (including underscores) are now silently dropped.

Ok, now to get your api_token value, you need to change your request header-field name to Api-Token (this is standard, you may read this).

Now you can access your Api-Token value via:

$request->header('Api-Token', 'any-default-value');

If you really want to get your non standard header definition, you may use getallheaders function. For more information, you may read Symfony\Component\HttpFoundation\ServerBag@getHeaders method.

krisanalfa
  • 6,268
  • 2
  • 29
  • 38