PHPackages                             tourze/access-token-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. tourze/access-token-bundle

ActiveSymfony-bundle[Authentication &amp; Authorization](/categories/authentication)

tourze/access-token-bundle
==========================

Token Manage

1.1.0(4mo ago)03.0k4MITPHPCI passing

Since May 10Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/access-token-bundle)[ Packagist](https://packagist.org/packages/tourze/access-token-bundle)[ RSS](/packages/tourze-access-token-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (39)Versions (8)Used By (4)

Access Token Bundle
===================

[](#access-token-bundle)

[English](README.md) | [中文](README.zh-CN.md)

[![Latest Version](https://camo.githubusercontent.com/738f4f8fe8741d498292dacd1581781ba099fdbecb4af1ff183e906d4dedda22/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f6163636573732d746f6b656e2d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/access-token-bundle)[![PHP Version](https://camo.githubusercontent.com/acffb6ae1962992d26e4466782832787e79504a6250f80d732c4283458b9f497/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d626c75652e737667)](https://packagist.org/packages/tourze/access-token-bundle)[![License](https://camo.githubusercontent.com/074b89bca64d3edc93a1db6c7e3b1636b874540ba91d66367c0e5e354c56d0ea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e737667)](LICENSE)[![Build Status](https://camo.githubusercontent.com/820a16a5e50f25159844922e342329aa7588d4bb1624c6887dcb756ac83db9e3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6f776e65722f7265706f2f63692e796d6c)](https://github.com/owner/repo/actions)[![Code Coverage](https://camo.githubusercontent.com/52007fa7878a7cfe4af314b17ed2a37a0fff4d4fa76e54b9b807f0155bd044be/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6f776e65722f7265706f)](https://codecov.io/github/owner/repo)

A Symfony bundle for managing access tokens with built-in security features, token lifecycle management, and API authentication support.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Setup](#setup)
- [API Usage](#api-usage)
- [Configuration Options](#configuration-options)
- [Advanced Examples](#advanced-examples)
- [API Reference](#api-reference)
- [Contributing](#contributing)
- [Testing](#testing)
- [License](#license)
- [References](#references)

Features
--------

[](#features)

- 🔐 **Secure Token Management** - Generate and manage secure access tokens for API authentication
- 🚫 **Multiple Login Prevention** - Optional feature to prevent users from having multiple active sessions
- 🔄 **Token Lifecycle Management** - Automatic token expiration and renewal
- 🧹 **Automatic Cleanup** - Built-in command to clean up expired tokens
- 🌐 **API Ready** - Pre-built API endpoints for token management
- 🛡️ **Symfony Security Integration** - Seamless integration with Symfony's security component
- 📱 **Device Tracking** - Track device information for each token
- ⚡ **High Performance** - Optimized database queries with Doctrine ORM

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Symfony 6.4 or higher
- Doctrine ORM 3.0 or higher

Installation
------------

[](#installation)

```
composer require tourze/access-token-bundle
```

Quick Start
-----------

[](#quick-start)

Get started with Access Token Bundle in just a few minutes:

### 1. Install and Setup

[](#1-install-and-setup)

```
# Install the bundle
composer require tourze/access-token-bundle

# Run database migration to create access token table
php bin/console doctrine:migrations:migrate
```

### 2. Configure Security (optional)

[](#2-configure-security-optional)

Add access token authentication to your `config/packages/security.yaml`:

```
security:
    firewalls:
        api:
            pattern: ^/api
            stateless: true
            access_token:
                token_handler: Tourze\AccessTokenBundle\Service\AccessTokenHandler
```

### 3. Create Your First Token

[](#3-create-your-first-token)

```
# Create an access token for a user via command line
php bin/console app:create-access-token your_username --expires=3600

# Or use the service in your code
use Tourze\Tourze\AccessTokenBundle\Service\AccessTokenService;

$token = $accessTokenService->createToken($user, 3600, 'My Device');
echo $token->getToken(); // Use this token for API calls
```

### 4. Test Your Token

[](#4-test-your-token)

```
# Test the token with curl
curl -H "Authorization: Bearer your_token_here" http://localhost/api/test
```

That's it! You now have working access token authentication for your Symfony application.

Setup
-----

[](#setup)

### Enable the Bundle

[](#enable-the-bundle)

If you're using Symfony Flex, the bundle is automatically enabled. Otherwise, add it to your `config/bundles.php`:

```
return [
    // ...
    Tourze\AccessTokenBundle\Tourze\AccessTokenBundle::class => ['all' => true],
];
```

### Configure Security

[](#configure-security)

Add the access token authentication to your security configuration:

```
# config/packages/security.yaml
security:
    firewalls:
        api:
            pattern: ^/api
            stateless: true
            access_token:
                token_handler: Tourze\AccessTokenBundle\Service\AccessTokenHandler
```

### Run Database Migration

[](#run-database-migration)

Create the access token table:

```
php bin/console doctrine:migrations:migrate
```

API Usage
---------

[](#api-usage)

### Basic Usage

[](#basic-usage)

1. **Create access token**

```
use Tourze\Tourze\AccessTokenBundle\Service\AccessTokenService;

// Inject service
$accessTokenService = $container->get(AccessTokenService::class);

// Create token for user (expires in 1 hour, device: iOS App)
$token = $accessTokenService->createToken($user, 3600, 'iOS App');
echo $token->getToken(); // Output token value
```

2. **Validate access token**

```
// Validate and extend token
$validToken = $accessTokenService->validateAndExtendToken($tokenValue, 3600);
if ($validToken) {
    // Token is valid
    $user = $validToken->getUser();
}
```

3. **Revoke token**

```
$accessTokenService->revokeToken($token);
```

### Command Line Tools

[](#command-line-tools)

1. Create access token

```
php bin/console app:create-access-token username --expires=3600 --device="Mobile App"
```

2. Cleanup expired tokens

```
php bin/console app:cleanup-access-tokens
php bin/console app:cleanup-access-tokens --dry-run  # View only, don't delete
```

### API Endpoints

[](#api-endpoints)

The bundle provides the following API endpoints:

- `GET /api/user` - Get current user information
- `GET /api/tokens` - Get all tokens for current user
- `POST /api/token/revoke/{id}` - Revoke specified token
- `GET /api/test` - Test API access

Configuration Options
---------------------

[](#configuration-options)

### Environment Variables

[](#environment-variables)

Configure the following environment variables in your `.env` file:

```
# Access token renewal time (seconds), default 3600 seconds (1 hour)
ACCESS_TOKEN_RENEWAL_TIME=3600

# Prevent multiple login, default true (prevent multiple login)
# true: Creating new token will automatically revoke all existing tokens for the user
# false: Allow user to have multiple valid tokens simultaneously
ACCESS_TOKEN_PREVENT_MULTIPLE_LOGIN=true
```

### Security Configuration

[](#security-configuration)

Configure access token authentication in `config/packages/security.yaml`:

```
security:
    firewalls:
        api:
            pattern: ^/api
            stateless: true
            access_token:
                token_handler: Tourze\AccessTokenBundle\Service\AccessTokenHandler
```

### Database Configuration

[](#database-configuration)

Make sure to run database migrations to create the access token table:

```
php bin/console doctrine:migrations:migrate
```

Advanced Examples
-----------------

[](#advanced-examples)

### Complete Login Flow Example

[](#complete-login-flow-example)

```
use Tourze\Tourze\AccessTokenBundle\Service\AccessTokenService;
use Symfony\Component\HttpFoundation\JsonResponse;

class AuthController extends AbstractController
{
    public function login(
        Request $request,
        UserPasswordHasherInterface $passwordHasher,
        AccessTokenService $accessTokenService
    ): JsonResponse {
        $username = $request->request->get('username');
        $password = $request->request->get('password');

        // Validate user credentials
        $user = $this->userRepository->findOneBy(['username' => $username]);
        if (!$user || !$passwordHasher->isPasswordValid($user, $password)) {
            return $this->json(['error' => 'Invalid username or password'], 401);
        }

        // Create access token
        $deviceInfo = $request->headers->get('User-Agent');
        $token = $accessTokenService->createToken($user, 86400, $deviceInfo);

        return $this->json([
            'access_token' => $token->getToken(),
            'expires_at' => $token->getExpiresAt()->format('Y-m-d H:i:s'),
            'user' => [
                'id' => $user->getId(),
                'username' => $user->getUsername(),
            ]
        ]);
    }
}
```

### Using Access Token to Call API

[](#using-access-token-to-call-api)

```
# Use Bearer Token authentication
curl -H "Authorization: Bearer your_access_token_here" \
     http://localhost/api/user
```

### Prevent Multiple Login Example

[](#prevent-multiple-login-example)

When `ACCESS_TOKEN_PREVENT_MULTIPLE_LOGIN=true`:

```
// User first login
$token1 = $accessTokenService->createToken($user, 3600, 'Web Browser');

// User login on another device, previous token will be automatically revoked
$token2 = $accessTokenService->createToken($user, 3600, 'Mobile App');

// Now $token1 is invalid, only $token2 is valid
```

When `ACCESS_TOKEN_PREVENT_MULTIPLE_LOGIN=false`:

```
// User can have multiple valid tokens simultaneously
$token1 = $accessTokenService->createToken($user, 3600, 'Web Browser');
$token2 = $accessTokenService->createToken($user, 3600, 'Mobile App');

// Both $token1 and $token2 remain valid
```

API Reference
-------------

[](#api-reference)

### Token Repository Methods

[](#token-repository-methods)

```
use Tourze\Tourze\AccessTokenBundle\Repository\AccessTokenRepository;

// Find tokens by user
$tokens = $accessTokenRepository->findByUser($user);

// Find active tokens
$activeTokens = $accessTokenRepository->findActiveTokensByUser($user);

// Count expired tokens
$expiredCount = $accessTokenRepository->countExpired();

// Delete expired tokens
$deletedCount = $accessTokenRepository->deleteExpired();
```

### Custom Token Validation

[](#custom-token-validation)

```
use Tourze\Tourze\AccessTokenBundle\Entity\AccessToken;

// Custom validation logic
$token = $accessTokenService->findToken($tokenValue);
if ($token && !$token->isExpired()) {
    // Additional custom checks
    if ($token->getDeviceInfo() === $expectedDevice) {
        // Token is valid for this device
    }
}
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

Testing
-------

[](#testing)

Run the test suite:

```
./vendor/bin/phpunit packages/access-token-bundle/tests
```

Run PHPStan analysis:

```
php -d memory_limit=2G ./vendor/bin/phpstan analyse packages/access-token-bundle
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

References
----------

[](#references)

- [Symfony Security Component](https://symfony.com/doc/current/security.html)
- [Doctrine ORM](https://www.doctrine-project.org/projects/orm.html)
- [Symfony Access Token Authenticator](https://symfony.com/doc/current/security/access_token.html)

###  Health Score

39

—

LowBetter than 85% of packages

Maintenance79

Regular maintenance activity

Popularity16

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~37 days

Recently: every ~48 days

Total

7

Last Release

141d ago

Major Versions

0.0.3 → 1.0.02025-11-01

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (2 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-access-token-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-access-token-bundle/health.svg)](https://phpackages.com/packages/tourze-access-token-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M647](/packages/sylius-sylius)[contao/core-bundle

Contao Open Source CMS

1231.6M2.3k](/packages/contao-core-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M151](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

7310.3k29](/packages/open-dxp-opendxp)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
