PHP code example of phpnomad / auth

1. Go to this page and download the library: Download phpnomad/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/ */

    

phpnomad / auth example snippets




namespace MyApp;

use MyApp\Auth\AppCurrentContextResolver;
use MyApp\Auth\AppCurrentUserResolver;
use MyApp\Auth\AppHashStrategy;
use MyApp\Auth\AppPasswordResetStrategy;
use MyApp\Auth\AppSecretProvider;
use PHPNomad\Auth\Interfaces\CurrentContextResolverStrategy;
use PHPNomad\Auth\Interfaces\CurrentUserResolverStrategy;
use PHPNomad\Auth\Interfaces\HashStrategy;
use PHPNomad\Auth\Interfaces\JwtStrategy;
use PHPNomad\Auth\Interfaces\PasswordResetStrategy;
use PHPNomad\Auth\Interfaces\SecretProvider;
use PHPNomad\JWT\Firebase\Integration\Strategies\FirebaseJwt;
use PHPNomad\Loader\Interfaces\HasClassDefinitions;

class AuthInitializer implements HasClassDefinitions
{
    public function getClassDefinitions(): array
    {
        return [
            AppCurrentContextResolver::class => CurrentContextResolverStrategy::class,
            AppCurrentUserResolver::class    => CurrentUserResolverStrategy::class,
            AppHashStrategy::class           => HashStrategy::class,
            AppPasswordResetStrategy::class  => PasswordResetStrategy::class,
            AppSecretProvider::class         => SecretProvider::class,
            FirebaseJwt::class               => JwtStrategy::class,
        ];
    }
}



use DateTime;
use PHPNomad\Auth\Builders\JwtPayloadBuilder;
use PHPNomad\Auth\Services\JwtService;

class IssueAccessToken
{
    public function __construct(protected JwtService $jwt) {}

    public function forUser(int $userId): string
    {
        $payload = (new JwtPayloadBuilder())
            ->setIssuer('my-app')
            ->setSubject((string) $userId)
            ->setIssuedAt(new DateTime('now'))
            ->setExpirationTime(new DateTime('+1 hour'))
            ->build();

        return $this->jwt->encodeJwt($payload);
    }
}