jwt-auth Documentation

JSON Web Token Authentication for Laravel & Lumen

11,486 stars PHP PHP 1 file ยท ~3,008 tokens #authentication#jwt#laravel#php
RAW Doc

Technical Documentation: tymondesigns/jwt-auth

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (README.md)

jwt-auth

JSON Web Token Authentication for Laravel








See the WIKI for documentation

License

The MIT License (MIT)

Copyright (c) 2014 Sean Tymon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


Auth Guard (`docs/auth-guard.md`)

Methods

The following methods are available on the Auth guard instance.

Multiple Guards

If the newly created 'api' guard is not set as a default guard or you have defined multiple guards to handle authentication,
you should specify the guard when calling auth().

php
$token = auth('api')->attempt($credentials);

attempt()

Attempt to authenticate a user via some credentials.

php
// Generate a token for the user if the credentials are valid
$token = auth()->attempt($credentials);

This will return either a jwt or null

login()

Log a user in and return a jwt for them.

php
// Get some user from somewhere
$user = User::first();

// Get the token
$token = auth()->login($user);

user()

Get the currently authenticated user.

php
// Get the currently authenticated user
$user = auth()->user();

If the user is not then authenticated, then null will be returned.

userOrFail()

Get the currently authenticated user or throw an exception.

php
try {
    $user = auth()->userOrFail();
} catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
    // do something
}

If the user is not set, then a Tymon\JWTAuth\Exceptions\UserNotDefinedException will be thrown

logout()

Log the user out - which will invalidate the current token and unset the authenticated user.

php
auth()->logout();

// Pass true to force the token to be blacklisted "forever"
auth()->logout(true);

refresh()

Refresh a token, which invalidates the current one

php
$newToken = auth()->refresh();

// Pass true as the first param to force the token to be blacklisted "forever".
// The second parameter will reset the claims for the new token
$newToken = auth()->refresh(true, true);

invalidate()

Invalidate the token (add it to the blacklist)

php
auth()->invalidate();

// Pass true as the first param to force the token to be blacklisted "forever".
auth()->invalidate(true);

tokenById()

Get a token based on a given user's id.

php
$token = auth()->tokenById(123);

payload()

Get the raw JWT payload

php
$payload = auth()->payload();

// then you can access the claims directly e.g.
$payload->get('sub'); // = 123
$payload['jti']; // = 'asfe4fq434asdf'
$payload('exp') // = 123456
$payload->toArray(); // = ['sub' => 123, 'exp' => 123456, 'jti' => 'asfe4fq434asdf'] etc

validate()

Validate a user's credentials

php
if (auth()->validate($credentials)) {
    // credentials are valid
}

More advanced usage

Adding custom claims

php
$token = auth()->claims(['foo' => 'bar'])->attempt($credentials);

Set the token explicitly

php
$user = auth()->setToken('eyJhb...')->user();

Set the request instance explicitly

php
$user = auth()->setRequest($request)->user();

Override the token ttl

php
$token = auth()->setTTL(7200)->attempt($credentials);

Configuration (`docs/configuration.md`)

Let's review some of the options in the config/jwt.php file that we published earlier.
I won't go through all of the options here since the file itself is pretty well documented.

First up is:

text
'secret' => env('JWT_SECRET'),

Coming soon...


Laravel Installation (`docs/laravel-installation.md`)

Install via composer

Run the following command to pull in the latest version:

bash
composer require tymon/jwt-auth

Add service provider ( Laravel 5.4 or below )

Add the service provider to the providers array in the config/app.php config file as follows:

php
'providers' => [

    ...

    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]

Publish the config

Run the following command to publish the package config file:

bash
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

You should now have a config/jwt.php file that allows you to configure the basics of this package.


Generate secret key

I have included a helper command to generate a key for you:

bash
php artisan jwt:secret

This will update your .env file with something like JWT_SECRET=foobar

It is the key that will be used to sign your tokens. How that happens exactly will depend
on the algorithm that you choose to use.


Lumen Installation (`docs/lumen-installation.md`)

Install via composer

Run the following command to pull in the latest version:

bash
composer require tymon/jwt-auth

Copy the config

Copy the config file from vendor/tymon/jwt-auth/config/config.php to config folder of your Lumen application and rename it to jwt.php

Register your config by adding the following in the bootstrap/app.php before middleware declaration.

php
$app->configure('jwt');

Bootstrap file changes

Add the following snippet to the bootstrap/app.php file under the providers section as follows:

php
// Uncomment this line
$app->register(App\Providers\AuthServiceProvider::class);

// Add this line
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

Then uncomment the auth middleware in the same file:

php
$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);

Generate secret key

I have included a helper command to generate a key for you:

bash
php artisan jwt:secret

This will update your .env file with something like JWT_SECRET=foobar

It is the key that will be used to sign your tokens. How that happens exactly will depend
on the algorithm that you choose to use.


Quick Start (`docs/quick-start.md`)

Before continuing, make sure you have installed the package as per the installation instructions for
Laravel or Lumen.

Update your User model

Firstly you need to implement the Tymon\JWTAuth\Contracts\JWTSubject contract on your User model,
which requires that you implement the 2 methods getJWTIdentifier() and getJWTCustomClaims().

The example below should give you an idea of how this could look. Obviously you should make any
changes, as necessary, to suit your own needs.

php
<?php

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

Configure Auth guard

Note: This will only work if you are using Laravel 5.2 and above.

Inside the config/auth.php file you will need to make a few changes to configure Laravel
to use the jwt guard to power your application authentication.

Make the following changes to the file:

php
'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

...

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

Here we are telling the api guard to use the jwt driver, and we are setting the api guard
as the default.

We can now use Laravel's built in Auth system, with jwt-auth doing the work behind the scenes!

Add some basic authentication routes

First let's add some routes in routes/api.php as follows:

php
Route::group([

    'middleware' => 'api',
    'prefix' => 'auth'

], function ($router) {

    Route::post('login', 'AuthController@login');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('me', 'AuthController@me');

});

Create the AuthController

Then create the AuthController, either manually or by running the artisan command:

bash
php artisan make:controller AuthController

Then add the following:

text
/* Detailed source-code truncated for AI context efficiency. */

You should now be able to POST to the login endpoint (e.g. http://example.dev/auth/login) with some valid
credentials and see a response like:

json
{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ",
    "token_type": "bearer",
    "expires_in": 3600
}

This token can then be used to make authenticated requests to your application.

Authenticated requests

There are a number of ways to send the token via http:

Authorization header

Authorization: Bearer eyJhbGciOiJIUzI1NiI...

Query string parameter

http://example.dev/me?token=eyJhbGciOiJIUzI1NiI...

Post parameter

Cookies

Laravel route parameter


Resources (`docs/resources.md`)

Over the last couple of years, the community has provided some great tutorials and packages that
have helped people get up and running with jwt-auth. So it's only right that I post some of them here.

Coming soon...


--- METRICS ---