Skip to content

Remove the challenge method from the AuthenticationMethodInterface #113

Description

@klsoft-web

Proposed new feature or change

Remove the challenge method from the AuthenticationMethodInterface. These methods violate the Interface segregation principle and lead to.
Code duplication:
https://github.com/yiisoft/user/blob/master/src/Method/ApiAuth.php#L22
https://github.com/yiisoft/user/blob/master/src/Method/WebAuth.php#L28

Redundunt code:
https://github.com/yiisoft/user/blob/master/src/Method/ApiAuth.php#L31
https://github.com/yiisoft/auth/blob/master/src/Method/HttpCookie.php#L38
https://github.com/yiisoft/auth/blob/master/src/Method/HttpHeader.php#L46
https://github.com/yiisoft/auth/blob/master/src/Method/QueryParameter.php#L35

Proposing refactoring:

//Yiisoft\Auth\AuthenticationMethodInterface.php
interface AuthenticationMethodInterface
{
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface;
}

//Yiisoft\Auth\Middleware\Authentication.php;
class Authentication implements MiddlewareInterface
{
    // ...

    public function __construct(
        private AuthenticationMethodInterface $authenticationMethod,
        private RequestHandlerInterface $authenticationFailureHandler
    ) {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $identity = $this->authenticationMethod->authenticate($request);
        $request = $request->withAttribute(self::class, $identity);

        if ($identity === null && !$this->isOptional($request)) {
            return $this->authenticationFailureHandler->handle($request);
        }

        return $handler->handle($request);
    }

    // ...
}

//Yiisoft\Auth\Handler\HttpBasicFailureHandler.php;
final class HttpBasicFailureHandler implements RequestHandlerInterface
{
    private string $realm = 'api';

    public function __construct(private AuthenticationFailureHandler $authenticationFailureHandler)
    {
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $response = $this->authenticationFailureHandler->handle($request);
        return $response->withHeader(Header::WWW_AUTHENTICATE, "Basic realm=\"{$this->realm}\"");;
    }

    public function withRealm(string $realm): self
    {
        $new = clone $this;
        $new->realm = $realm;
        return $new;
    }
}

//Yiisoft\Auth\Middleware\HttpBasicAuthentication.php;
final class HttpBasicAuthentication extends Authentication
{
    public function __construct(
        HttpBasic $httpBasic,
        HttpBasicFailureHandler $httpBasicFailureHandler
    ) {
        parent::__construct($httpBasic, $httpBasicFailureHandler);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions