agven/symfony-jwt-auth

JWT Authentication Bundle for Symfony REST API

Installs: 963

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

Type:symfony-bundle

dev-master 2019-08-14 09:02 UTC

This package is auto-updated.

Last update: 2024-11-14 20:54:17 UTC


README

Lightweight JWT Authentication Bundle. The bundle also provides Refresh and Access tokens.

Installation

composer require agven/symfony-jwt-auth

or add agven/symfony-jwt-auth to your composer.json file. This bundle using the firebase/php-jwt library for decode and encode jwt token.

Configure your security.yml :

security:
    # ...
    firewalls:
        auth:
            pattern: ^/api/auth
            anonymous: true
            stateless: true
        api:
            pattern: ^/api
            stateless: true
            guard:
                authenticators:
                    - Agven\JWTAuthBundle\Security\TokenAuthenticator
    # ...            
    access_control:
        - { path: ^/api/auth,  roles: IS_AUTHENTICATED_ANONYMOUSLY, methods: [POST] }
        - { path: ^/api,       roles: ROLE_ADMIN }

You can get the token for user with service like this:

// ...
use Agven\JWTAuthBundle\Core\Services\Manager\TokenInterface as TokenManagerInterface;
// ...

class AuthManager
{
    private $tokenManager;
    
    public function __construct(TokenManagerInterface $tokenManager) 
    {
        $this->tokenManager = $tokenManager;
    }
    
    public function auth(string $username, string $password)
    {
        $user = $this->userRepository->findOneByUsername($username);
        if (!$user) {
            throw new EntityNotFoundException('User not found.');
        }
        
        // ...
        // Validate password or todo something else
        // ...
        
        $token = $this->tokenManager->createAccessToken($user);
    }

To Do

  • Add tests.
  • Improve documentation.