2

Problem: I need to implement a basic authentication on my API created with Laravel 5.4. Since we need to implement it without a database (just getting credentials from config()), I tried to create a registered middleware like the following one:

<?php namespace App\Http\Middleware; class AuthenticateOnceWithBasicAuth { public function handle($request, $next) { if($request->getUser() != conf('auth.credentials.user') && $request->getPassword() != conf('auth.credentials.pass')) { $headers = array('WWW-Authenticate' => 'Basic'); return response('Unauthorized', 401, $headers); } return $next($request); } } 

It works, but this way I can only have one credentials for the whole API. I've tried to create more then one credentials in the config, saving user and password from request, but this way, it works like basic auth is disabled.

Question: is there any way to achieve this? How can I have multiple credentials in my config file, without using a database?

1
  • There is an issue with this code! You are returning 401 only in the case that both username AND password does not match. If a user provides a valid username, but invalid password he gets authenticated. you should use || instead of && Commented Jul 31, 2017 at 9:57

2 Answers 2

5

You can save your authorized usernames and password in your config file as a Collection.

config/myconfig.php

return [ 'authorized_identities' => collect([ ['user1','password1'], ['user2','password2'], ... ]), ]; 

and then in your middleware

if(config('myconfig.authorized_identites')->contains([$request->getUser(),$request->getPassword()])) 
Sign up to request clarification or add additional context in comments.

4 Comments

Another option is to put it into a singleton.
i am using Lumen 5.6 and config() returns an array, so collect(config()) is the safest way IMO
It gives below error In ConfigCacheCommand.php line 71: Your configuration files are not serializable. In Macroable.php line 76: Method Illuminate\Support\Collection::__set_state does not exist.
That error means you have a closure in your configuration file, at the time of writing the above code, the collect() method was allowed in the configuration file, try to remove it and/or remove any closure you added in your configuration file.
0

You can have an array of credentials and try to match the input with anyone of them and validate. To be honest you could easily implement this with a sqlite database. It requires minimalistic setup and you can get started and use it within 5 mins.

1 Comment

It could be the case where he cant use a sqlite db either, since that requires sqlite3. But I agree with the array approach, should be simple enough.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.