agpilot/jwt-auth-bundle

JWT Authentication Bundle for Symfony REST API

1.0.4 2016-11-20 17:21 UTC

README

JWT Authentication Bundle for Symfony 3

Installation

php composer.phar require "agpilot/jwt-auth-bundle"

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

Register the bundle in app/AppKernel.php:

public function registerBundles()
{
    return array(
        // ...
        new AGPilot\Bundle\JWTAuthBundle(),
    );
}

Configure your parameters.yml.dist :

jwt_alg:            "HS256"        # algorithm
jwt_private_key:    "%app.secret%" # private key
jwt_token_lifetime: 3600

Configure your security.yml :

security:
    # ...
    
    firewalls:
        auth:
            pattern: ^/api/auth
            anonymous: true
            stateless: true
        api:
            pattern: ^/api
            stateless: true
            guard:
                authenticators:
                    - agpilot.token_authenticator
    providers:
        api_provider:
            id: app.security.api_token_user_provider
            
    access_control:
        - { path: ^/api/auth,  roles: IS_AUTHENTICATED_ANONYMOUSLY, methods: [POST] }
        - { path: ^/api,       roles: ROLE_ADMIN }

You must to create a custom User Provider - providers:api_provider, the only requirement is that the class implements UserProviderInterface.

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

// ...
use AGPilot\JWTAuthBundle\Core\Services\Managers\JWTManagerInterface;

class UserRegistry
{
    private $jwtManager;
    
    public function __construct(JWTManagerInterface $jwtManager) 
    {
        $this->jwtManager = $jwtManager;
    }
    
    public function auth(UserAuthRequest $userAuth)
    {
        $user = $this->userRepository->findOneByUsername($userAuth->username);
        if (!$user) {
            throw new EntityNotFoundException('User not found.');
        }
        // ...
        $token = $this->jwtManager->createToken($user);
        return $token;
    }

To Do

  • Add tests.
  • Improve documentation.