PHPackages                             attla/token - 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. attla/token

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

attla/token
===========

Turn everything into a unique encrypted JWT.

03PHP

Since Jan 21Pushed 1y ago1 watchersCompare

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

READMEChangelogDependenciesVersions (1)Used By (0)

Web Token
=========

[](#web-token)

[![License](https://camo.githubusercontent.com/891419a00e04aa0e311068fa8a04eec92cab4f7026c76278279bf2a1da50e578/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d6c69676874677265792e737667)](LICENSE)[![Latest Stable Version](https://camo.githubusercontent.com/187f18b71a57f6e09111341eac36a4f3841cdf553566771b8487fc9b2bee0871/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6174746c612f746f6b656e)](https://packagist.org/packages/attla/token)[![Total Downloads](https://camo.githubusercontent.com/7a15b9c7d3906454fd472cebb52c09442a422c41aaab6835bfd7b7f7f380c01b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6174746c612f746f6b656e)](https://packagist.org/packages/attla/token)

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

[](#installation)

```
composer require attla/token
```

Usage
-----

[](#usage)

#### Creating and managing a token:

[](#creating-and-managing-a-token)

```
use Attla\Token\Factory as Token;
use Attla\Token\Facade as TokenFacade;

// create token on PHP projects
$token = Token::create();
// on laravel projects
$token = TokenFacade::create();
// or with global alias on laravel projects
$token = \Token::create();

// set a payload
$token->body('token value..');

// get the token value
$tokenEncoded = $token->get();
```

#### Configure the token instance:

[](#configure-the-token-instance)

```
$token = Token::create()->secret('your secret phrase');
// changing the secret on exist instance
$token->secret('your secret phrase');

// secret aliases
$token->phrase('your secret phrase');
$token->passphrase('your secret phrase');

// Set token body type when it can be converted (array, stdClass, object)
$token->associative(); // set token payload as associative array
$token->asObject();    // set payload as stdClass object

// defines that it will always generate the same result
$token->same();
```

By default the `secret` key is empty, but on laravel projects the default as `env('APP_KEY')` or `config('app.key')`

When token body as `string`, `integer`, `float`, `bool`, and `null`, it cant be converted to associative or object equivalent

#### Setup token claims:

[](#setup-token-claims)

Set the `expiration` time in seconds after which the JWT MUST NOT be accepted for processing:

```
use Carbon\Carbon;

$time = strtotime('+1 hour');

$token->exp($time);
$token->expiration((new \DateTime())->setTimeStamp($time));
$token->expiresAt(Carbon::createFromTimestamp($time));
```

Set the time at which the JWT was issued (`iat`):

```
use Carbon\Carbon;

$time = strtotime('-1 day');

$token->iat($time);
$token->issuedAt((new \DateTime())->setTimeStamp($time));
$token->issuedBefore(Carbon::createFromTimestamp($time));
```

Set the time before (`nbf`) which the JWT MUST NOT be accepted for processing

```
use Carbon\Carbon;

$time = strtotime('+30 day');

$token->nbf($time);
$token->notBefore((new \DateTime())->setTimeStamp($time));
$token->canOnlyBeUsedAfter(Carbon::createFromTimestamp($time));
```

Set the `audience` that the JWT is intended for:

```
$token->aud('https://example.com');
$token->audience('https://example.com', 'https://example.app');
$token->permittedFor(['https://example.net', 'https://example.org']);
```

Set the principal `subject` of the JWT:

```
$token->relatedTo('exampl@e.com');
$token->sub('exampl@e.com');
```

Set the principal that issued (`iss`) the JWT:

```
$token->issuedBy('https://example.com');
$token->iss('https://example.net');
```

Set the unique identifier (`jti`) for the JWT:

```
$jti = hash('sha256', uniqid(mt_rand(), true));

$token->jti($jti);
$token->identifiedBy($jti);
```

#### Custom validation claims:

[](#custom-validation-claims)

Lock the token by `browser` user agent:

```
// current browser
$token->bwr();
$token->broser();

// setup a user agent by string
$token->browser('Mozilla/5.0 (U; Linux x86_64; en-US) Gecko/20100101 Firefox/50.9');
```

Lock the token by `ip` address:

```
// current request ip address
$token->ip();

// setup a ip address by string
$token->ip('1.1.1.1');
$token->ip('1.1.1.1', '2001:db8:0:0:0:0:2:1');
$token->ip(['1.1.1.1', '8.8.8.8']);
```

Lock the token by geographic coordinates (`loc`):

```
// setup a location by coordinate string
$token->loc('-44.05964,77.10679,5');
```

#### Setup custom claim:

[](#setup-custom-claim)

```
// set a custom claim "uid"
$token->withClaim('uid', 1);
$token->with('uid', 1); // alias

// on parse validate using:
$token->with('uid', 1);
```

All claim values as inserted on token header, to be retrieved on body use:

```
// insert the payload as array or object
$token->payload(['uid' => 1]);

// on parse validate use:
$token->with('uid', 1);
```

Verifying if a value is present on token:

```
$hasUid = $token->has('uid'); // isset(uid)
$hasUidWithValue = $token->has('uid', 1); // isset(uid) && uid === 1
```

#### Parse a token:

[](#parse-a-token)

```
$tokenValue = Token::parse($tokenEncoded)
    ->associative()
    ->get();
```

#### Real world example:

[](#real-world-example)

```
// Creating
$token = Token::create()
    ->secret('your secret phrase')            // secret key
    ->iss($_SERVER['HTTP_HOST'])              // Set 'issuer' claim
    ->aud('e.com', $_SERVER['HTTP_HOST'])     // Set 'audience' claim
    ->sub('7urkg6uDkMISjZBuFGdeySokAIrSuWAB') // Set 'subject' claim
    ->iat(time()) // Set 'issued' date in seconds
    ->exp(7200)   // Set 'expiration' in seconds (2 hours)
    ->bwr()       // Lock the token by user agent of browser
    ->ip()        // Lock the token with IP (v6 or v4)
    ->payload([   // Set the token payload
        'name' => 'Acme LLC',
        'email' => 'acme@e.com',
    ]);

// Get the token
$tokenEncoded = $token->get();
echo $tokenEncoded . PHP_EOL;

$tokenParse = Token::parse($tokenEncoded)
    ->iss($_SERVER['HTTP_HOST']) // Set the issuer claim for validate
    ->validAt(time() - 3600)     // Rewrites the current date for 'exp', 'iat', 'nbf' validations
    ->associative();

if ($tokenParse->isValid()) {
    echo 'Subject: '. $tokenParse->sub() . PHP_EOL;
    echo 'Audience: '. implode(',', $tokenParse->audience()) . PHP_EOL;
    echo $tokenParse->get() . PHP_EOL;
} else {
    echo "Token as invalid!" . PHP_EOL;
}
```

License
-------

[](#license)

This package is licensed under the [MIT license](LICENSE) © [Zunq](https://zunq.com).

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance32

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity16

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/682727?v=4)[Andre Goncalves](/maintainers/nicolau)[@nicolau](https://github.com/nicolau)

---

Top Contributors

[![nicxlau](https://avatars.githubusercontent.com/u/17990891?v=4)](https://github.com/nicxlau "nicxlau (7 commits)")

### Embed Badge

![Health badge](/badges/attla-token/health.svg)

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

###  Alternatives

[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[league/oauth1-client

OAuth 1.0 Client Library

99698.8M106](/packages/league-oauth1-client)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[gesdinet/jwt-refresh-token-bundle

Implements a refresh token system over Json Web Tokens in Symfony

70516.4M35](/packages/gesdinet-jwt-refresh-token-bundle)[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

41721.2M118](/packages/league-oauth2-google)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)

PHPackages © 2026

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