PHPackages                             tfleet/tf-auth-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. tfleet/tf-auth-token

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

tfleet/tf-auth-token
====================

Auth token management

1.0.1(10y ago)0620MITPHPPHP &gt;=5.3.0

Since Jun 30Pushed 10y ago1 watchersCompare

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

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

Laravel 4 Auth token
====================

[](#laravel-4-auth-token)

Hooks into the laravel auth module and provides an auth token upon success. This token is really only secure in https environment. This main purpose for this module was to provide an auth token to javascript web app which could be used to identify users on api calls.

Upgrading to Laravel 4.1?, see the [breaking changes](#changes)

Based on .

Getting Started
---------------

[](#getting-started)

### Setup

[](#setup)

Add the package to your `composer.json`

```
"require": {
	...
    "tfleet/tf-auth-token": "dev-master"
}

```

Add the service provider to `app/config/app.php`

```
'tfleet\AuthToken\AuthTokenServiceProvider',

```

Setup the optional aliases in `app/config/app.php`

```
'AuthToken' => 'TFleet\Support\Facades\AuthToken',
'AuthTokenNotAuthorizedException' => 'TFleet\AuthToken\Exceptions\NotAuthorizedException'

```

Currently the auth tokens are stored in the database, you will need to run the migrations:

```
php artisan migrate --package=tfleet/tf-auth-token

```

##### Optional configuration

[](#optional-configuration)

This package defaults to using email as the username field to validate against, this can be changed via the package configuration.

1. Publish the configuration `php artisan config:publish tfleet/laravel-auth-token`
2. Edit the `format_credentials` closure in `app/config/packages/tfleet/laravel-auth-token/config.php`

Example - Only validate active users and check the username column instead of email:

```
'format_credentials' => function ($username, $password) {
	return array(
		'username' => $username,
		'password' => $password,
		'active' => true
	);
}

```

You can read more about the laravel Auth module here: [Authenticating Users](http://laravel.com/docs/security#authenticating-users)

### The controller

[](#the-controller)

A default controller is provided to grant, check and revoke tokens. Add the following to `app/routes.php`

```
Route::get('auth', 'Tfleet\AuthToken\AuthTokenController@index');
Route::post('auth', 'Tfleet\AuthToken\AuthTokenController@store');
Route::delete('auth', 'Tfleet\AuthToken\AuthTokenController@destroy');

```

### CORS Support

[](#cors-support)

CORS support is not built into this library by default, it can be enabled by using the following package: [barryvdh/laravel-cors](https://github.com/barryvdh/laravel-cors).

The configuration will be specific to how your routing is setup. If you are using the `X-Auth-Token` header, it is important to add this to the `allowedHeaders` configuration. See the package documentation for further configuration details.

Heres an example using the default `auth` route:

```
'paths' => array(
    'auth' => array(
        'allowedOrigins' => array('*'),
        'allowedHeaders' => array('Content-Type', 'X-Auth-Token'),
        'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
        'maxAge' => 3600,
    )
),

```

> Note: If you know the list of `allowedOrigins` it might be best to define them explicitly instead of using the wildcard `*`

##### Request parameters

[](#request-parameters)

All request must include one of:

1. `X-Auth-Token` header.
2. `auth_token` field.

##### `GET` Index action

[](#get-index-action)

Returns current user as json. Requires auth token parameter to be present. On Fail throws `NotAuthorizedException`.

##### `POST` Store action

[](#post-store-action)

Required input `username` and `password`. On success returns json object containing `token` and `user`. On Fail throws `NotAuthorizedException`.

##### `DELETE` Destroy action

[](#delete-destroy-action)

Purges the users tokens. Requires auth token parameter to be present. On Fail throws `NotAuthorizedException`.

`NotAuthorizedException` has a `401` error code by default.

### Route Filter

[](#route-filter)

An `auth.token` route filter gets registered by the service provider. To protect a resource just register a before filter. Filter will throw an `NotAuthorizedException` if a valid auth token is invalid or missing.

```
Route::group(array('prefix' => 'api', 'before' => 'auth.token'), function() {
  Route::get('/', function() {
    return "Protected resource";
  });
});

```

### Events

[](#events)

The route filter will trigger `auth.token.valid` with the authorized user when a valid auth token is provided.

```
Event::listen('auth.token.valid', function($user)
{
  //Token is valid, set the user on auth system.
  Auth::setUser($user);
});

```

AuthTokenController::store will trigger `auth.token.created` before returning the response.

```
Event::listen('auth.token.created', function($user, $token)
{
	$user->load('relation1', 'relation2');
});

```

AuthTokenController::destroy will trigger `auth.token.deleted` before returning the response.

### Handling the NotAuthorizedException

[](#handling-the-notauthorizedexception)

Optionally register the `NotAuthorizedException` as alias eg. `AuthTokenNotAuthorizedException`

```
App::error(function(AuthTokenNotAuthorizedException $exception) {
  if(Request::ajax()) {
    return Response::json(array('error' => $exception->getMessage()), $exception->getCode());
  }

  …Handle non ajax response…
});

```

Combining Laravel Auth with AuthToken
-------------------------------------

[](#combining-laravel-auth-with-authtoken)

Some apps might already be using the traditional laravel based auth. The following can be used to manually generate a token.

```
if(Auth::check()) {
  $authToken = AuthToken::create(Auth::user());
  $publicToken = AuthToken::publicToken($authToken);
}

```

The `AuthToken::publicToken` method prepares the auth token to be sent to the browser.

Changes
-------

[](#changes)

*dev-master*

- Added token expiration parameter, token are only valide for a given period of time.
- Added user-agent support, a token is now linked to a user and a user agent. Each device can have is own token for the same user.

*0.3.0*

- Added `auth.token.created` event which gets triggered before response is returned in AuthTokenController::store
- AuthTokenController requires the event dispatcher to be passed to constructor.

*0.2.0*

- Adds support for Laravel 4.1.X. This is a hard dependency due to API changes in L4.1
- Removed the facade for AuthTokenController, must use the full namespace to controller. see [The controller section](#the-controller)
- Optional configuration for Auth::attempt fields.

Pro tip: Using with jQuery
--------------------------

[](#pro-tip-using-with-jquery)

Using the jQuery ajaxPrefilter method the X-Auth-Token can be set automatically on ajax request.

```
// Register ajax prefilter. If app config contains auth_token will automatically set header,
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  if (config.auth_token) {
    jqXHR.setRequestHeader('X-Auth-Token', config.auth_token);
  }
});

```

If a 401 response code is recieved it can also handled automatically. In the following example I opted to redirect to logout page to ensure user session was destroyed.

```
// If a 401 http error is recieved, automatically redirect to logout page.
$(document).ajaxError(function (event, jqxhr) {
  if (jqxhr && jqxhr.status === 401) {
    window.location = '/logout';
  }
});

```

Pro tip: Automatically binding token data to view.
--------------------------------------------------

[](#pro-tip-automatically-binding-token-data-to-view)

View composer can be used to automatically bind data to views. This keeps logic all in one spot. I use the following to setup config variables for javascript.

```
View::composer('layouts.default', function($view)
{
  $rootUrl = rtrim(URL::route('home'), '/');

  $jsConfig = isset($view->jsConfig) ? $view->jsConfig : array();

  $jsConfig = array_merge(array(
    'rootUrl' =>  $rootUrl
  ), $jsConfig);

  if(Auth::check()) {

    $authToken = AuthToken::create(Auth::user());
    $publicToken = AuthToken::publicToken($authToken);

    $userData = array_merge(
      Auth::user()->toArray(),
      array('auth_token' => $publicToken)
    );

    $jsConfig['userData'] = $userData;
  }

  $view->with('jsConfig', $jsConfig);
});

```

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity58

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

Unknown

Total

1

Last Release

3969d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5ac6eb338429e9335f0d2741dad1b67b1bc6d0efe00ddbeabadc9482afb3b72e?d=identicon)[tfleet](/maintainers/tfleet)

---

Top Contributors

[![yayann](https://avatars.githubusercontent.com/u/204421?v=4)](https://github.com/yayann "yayann (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/tfleet-tf-auth-token/health.svg)

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

###  Alternatives

[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)[olssonm/l5-very-basic-auth

Laravel stateless HTTP basic auth without the need for a database

1662.5M1](/packages/olssonm-l5-very-basic-auth)[stechstudio/laravel-jwt

Helper package that makes it easy to generate, consume, and protect routes with JWT tokens in Laravel

126117.6k](/packages/stechstudio-laravel-jwt)[scaler-tech/laravel-saml2

SAML2 Service Provider integration for Laravel applications, based on OneLogin toolkit

2737.5k](/packages/scaler-tech-laravel-saml2)[truckersmp/steam-socialite

Laravel Socialite provider for Steam OpenID.

1516.7k](/packages/truckersmp-steam-socialite)

PHPackages © 2026

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