Performing a Stateless HTTP Basic Login

Problem

You want to authenticate the user using HTTP basic authentication.

But you don't want cookies or the session to be used.

Solution

Use the Auth::onceBasic() method.

This operates just like Auth::basic() but instead of "logging in" the user is available for the current request only.

You can use it without any arguments and it will try matching the HTTP auth user to the email.

$result = Auth::onceBasic();
if ($result)
{
    throw new Exception('invalid credentials');
}

If the user field is something other than 'email' you can specify it with the first argument.

$result = Auth::onceBasic('username');
if ($result)
{
    throw new Exception('invalid credentials');
}

You can even pass the actual request you want to use. Normally, it uses the current request.

$result = Auth::onceBasic('email', $request);

Regardless of the method you use, the method returns a Response which you can pass back to the user for a 401 Invalid Credentials error.

Discussion

This is ideal to set up a filter for API authentication.

Here's a sample auth.api filter.

Route::filter('auth.api', function()
{
  return Auth::onceBasic();
});

By adding this filter to REST API routes, the request will return immediately with a 401 Invalid Credentials error when not authenticated, but will not store authentication details in a cookie or the session.

comments powered by Disqus