PHP code example of yiisoft / auth

1. Go to this page and download the library: Download yiisoft/auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yiisoft / auth example snippets


$identityRepository = getIdentityWithTokenRepository(); // \Yiisoft\Auth\IdentityRepositoryInterface
$authenticationMethod = new \Yiisoft\Auth\Method\HttpBasic($identityRepository);

$middleware = new \Yiisoft\Auth\Middleware\Authentication(
    $authenticationMethod,
    $responseFactory, // PSR-17 ResponseFactoryInterface
    $failureHandler // optional, \Yiisoft\Auth\Handler\AuthenticationFailureHandler by default
);

$middlewareDispatcher->addMiddleware($middleware);

public function actionIndex(\Psr\Http\Message\ServerRequestInterface $request): \Psr\Http\Message\ResponseInterface
{
    $identity = $request->getAttribute(\Yiisoft\Auth\Middleware\Authentication::class);
    // ...
}

$authenticationMethod = (new \Yiisoft\Auth\Method\HttpBasic($identityRepository))
    ->withRealm('Admin')
    ->withAuthenticationCallback(static function (
        ?string $username,
        ?string $password,
        \Yiisoft\Auth\IdentityWithTokenRepositoryInterface $identityRepository
    ): ?\Yiisoft\Auth\IdentityInterface {
        return $identityRepository->findIdentityByToken($username, \Yiisoft\Auth\Method\HttpBasic::class);
    });

$authenticationMethod = new \Yiisoft\Auth\Method\HttpBearer($identityRepository);

 $authenticationMethod = (new \Yiisoft\Auth\Method\HttpHeader($identityRepository))
     ->withHeaderName('X-Api-Key')
     ->withPattern('/(.*)/'); // default

$authenticationMethod = (new \Yiisoft\Auth\Method\QueryParameter($identityRepository))
    ->withParameterName('token');

$authenticationMethod = new \Yiisoft\Auth\Method\Composite([
    $bearerAuthenticationMethod,
    $basicAuthenticationMethod
]);