0

I'm building an API in Laravel and am attempting to use HTTP basic authentication. I've created a user with the email/password combination of [email protected]:testpass. I'm accessing an endpoint at the following URL which requires authentication: https://[email protected]:[email protected]/users/2

When I attach the auth.basic route filter to this route, I can successfully authenticate and access the authenticated user's details through the Auth class, however since this is an API I want to use stateless HTTP basic authentication, so I wrote my own filter:

// Our own auth filter to use onceBasic and return a consistent API response
Route::filter('basic.once', function() {
    $result = Auth::onceBasic();

    if ($result->getStatusCode() === 401) {
        // Unauthorized, return our own response
        return Response::json([
            'message' => 'Bad credentials'
        ], Config::get('status.error.unauthorized'));
    }

    return $result;
});

No matter what, the result of Auth::onceBasic() here always returns unauthorized, even though the username/password combination I'm sending stays the same. Even if I change Auth::onceBasic() to Auth::basic() in my filter it still returns unauthorized.

I don't even know where to start debugging this as my filter is essentially the same as the auth.basic filter that ships with Laravel, albeit with a bit more code to produce a consistent API output.

2
  • Could you post your user model? Also, is your password in the db hashed? Commented Nov 4, 2014 at 20:55
  • Did you solve it? Did you try to change the .httaccess? Commented Nov 24, 2014 at 18:33

1 Answer 1

1

Are you using PHP FastCGI?

From the official Laravel documentation:


https://laravel.com/docs/5.3/authentication#http-basic-authentication

A Note On FastCGI

If you are using PHP FastCGI, HTTP Basic authentication may not work correctly out of the box. The following lines should be added to your .htaccess file:

RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

I managed to solve it myself this way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.