master

laravel/framework

Last updated at: 29/12/2023 09:20

AuthenticateWithBasicAuth.php

TLDR

This file is part of the Illuminate\Auth\Middleware namespace and contains the AuthenticateWithBasicAuth class. This class is a middleware that handles basic authentication with a username and password. It takes in a request, a closure, and optional parameters for the guard and authentication field.

Methods

using

This is a static method of the AuthenticateWithBasicAuth class. It specifies the guard and field for the middleware. It takes in two optional parameters, $guard and $field, and returns a string.

handle

This method is used to handle an incoming request. It takes in a Request object, a Closure, and optional parameters for the guard and field. It uses the guard method of the Auth class to perform basic authentication with the specified guard and field. If the field is not provided, it defaults to "email". It then passes control to the next middleware in the pipeline.

<?php

namespace Illuminate\Auth\Middleware;

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

class AuthenticateWithBasicAuth
{
    /**
     * 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;
    }

    /**
     * Specify the guard and field for the middleware.
     *
     * @param  string|null  $guard
     * @param  string|null  $field
     * @return string
     *
     * @named-arguments-supported
     */
    public static function using($guard = null, $field = null)
    {
        return static::class.':'.implode(',', func_get_args());
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @param  string|null  $field
     * @return mixed
     *
     * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
     */
    public function handle($request, Closure $next, $guard = null, $field = null)
    {
        $this->auth->guard($guard)->basic($field ?: 'email');

        return $next($request);
    }
}