zot24's avatar

[L5.1][Unit Test] basic authentication `be` from tests when using `onceBasic` as middleware doesn't work

I need to access my end points authenticated, however it's seems like is not working properly, I'm doing this from my controllers:

$this->actingAs($user)->getJson("api/v1/contacts");

$this->assertResponseOk();

or

$this->be($user);
$this->getJson("api/v1/contacts");

$this->assertResponseOk();

However I don't get authenticated and I'm always receiving a 404

This is how my Middleware looks like:

return $this->auth->onceBasic('username') ?: $next($request);

I need oneBasic because I'm building an API

0 likes
3 replies
zot24's avatar

I did some research and tests and if I change it to

return $this->auth->basic('username') ?: $next($request);

Instead of

return $this->auth->onceBasic('username') ?: $next($request);

My test works, why is basic working and onceBasic don't? :S

pixelpeter's avatar

In Laravel 5.2 this issue still exists.

I worked around this by using $this->auth->basic() and NOT using the web middleware group for all api related routes in routes.php. This way no cookies or session vars get set!

schnittstabil's avatar

The following middleware works for me (based on Illuminate\Auth\Middleware\AuthenticateWithBasicAuth)

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as AuthFactory;

class AuthenticateOnceWithBasicAuth
{
    /**
     * The guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(AuthFactory $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $guard = $this->auth->guard($guard);

        if ($guard->check()) {
            return $next($request);
        }

        return $guard->onceBasic() ?: $next($request);
    }
}

Please or to participate in this conversation.