PHPackages                             bytesflipper/laravel-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. bytesflipper/laravel-auth-token

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

bytesflipper/laravel-auth-token
===============================

52813PHP

Since Jul 8Pushed 12y ago3 watchersCompare

[ Source](https://github.com/BytesFlipper/laravel-auth-token)[ Packagist](https://packagist.org/packages/bytesflipper/laravel-auth-token)[ RSS](/packages/bytesflipper-laravel-auth-token/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependenciesVersions (1)Used By (0)

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

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

Hoooks 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.

[![Build Status](https://camo.githubusercontent.com/5cdc718962d2b6d52e55040f4f50703d83f823958efe827bafe6b880261dc8f7/68747470733a2f2f7472617669732d63692e6f72672f746170706c6562792f6c61726176656c2d617574682d746f6b656e2e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/tappleby/laravel-auth-token)

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

[](#getting-started)

### Setup

[](#setup)

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

```
'Tappleby\AuthToken\AuthTokenServiceProvider',

```

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

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

```

### 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', 'AuthTokenController@index');
Route::post('auth', 'AuthTokenController@store');
Route::delete('auth', 'AuthTokenController@destroy');

```

##### `GET` Index action

[](#get-index-action)

Returns current user as json. Requires the `X-Auth-Token` header 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 the `X-Auth-Token` header 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 `X-Auth-Token` is invalid or not present.

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

```

### Token valid event

[](#token-valid-event)

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);
});

```

### Handling the NotAuthorizedException

[](#handling-the-notauthorizedexception)

Optionalliy 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.

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

25

—

LowBetter than 36% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.6% 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://www.gravatar.com/avatar/0834ce6ccc2fe863c0db69ed15b19b419b177fc3d4288ca0b16ee463fcd02d89?d=identicon)[BytesFlipper](/maintainers/BytesFlipper)

---

Top Contributors

[![tappleby](https://avatars.githubusercontent.com/u/1435253?v=4)](https://github.com/tappleby "tappleby (25 commits)")[![rajivseelam](https://avatars.githubusercontent.com/u/1103649?v=4)](https://github.com/rajivseelam "rajivseelam (2 commits)")

### Embed Badge

![Health badge](/badges/bytesflipper-laravel-auth-token/health.svg)

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

###  Alternatives

[kartik-v/yii2-password

Useful password strength validation utilities for Yii Framework 2.0

761.2M17](/packages/kartik-v-yii2-password)

PHPackages © 2026

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