JSON web token authentication for Lumen 5 using tymon/jwt-auth

Implementing the JWT (JSON Web Token) into Lumen 5.3 seems to be a bit of confusing area for most developers right now due to the changes in both Lumen and tymon/jwt-auth.

You probably want JWT to use it together with Socialite (Facebook, GitHub, … integration), AngularJs, … It is already a IETF standard, so using it is a good idea (congrats!).

The steps I describe here will give you a working example with:

  • Lumen 5.3
  • jwt-auth 1.0.0-beta.1

I verified that it works equally fine with Lumen 5.2 and previous alpha versions of jwt-auth. You could use even older versions of jwt-auth, but it now integrates with Lumen/Laravel’s guard system and makes your life much much easier; it will in essence allow you to use the “normal” Lumen authorization services, which will be smart enough to use JWT “under the hood”. DO IT!

Github repo

If you don’t want to read the whole thing, you can just check the repo I created for you in github.

It contains the very same code I put here, and I even took care of splitting the process in different commits to make it easier to dissect.

https://github.com/akaita/json-web-token-authentication-for-lumen-5

Preparation

In this section we will: - Create a Lumen 5.3 project - Create a database - Create some users

If you already know Lumen, you should just jump forward the next section.

The offical Lumen/Laravel documentation already gives very good information on how to create and deploy Lumen, so I won’t explain much.

I like creating the project doing:

composer create-project --prefer-dist laravel/lumen:"^5.3" lumen-jwt

Then, I copy the configuration:

cd lumen-jwt
cp .env.example .env

Development is much more comfortable when using SQLite and file-based caching, so change .env to:

    APP_ENV=local
    APP_DEBUG=true
    APP_KEY=XRyRe3QFqXh91emMHfjCVywTwXojPvjr
    
    DB_CONNECTION=sqlite
    DB_HOST=localhost
    DB_USERNAME=homestead
    DB_PASSWORD=secret
    
    CACHE_DRIVER=file

Beware: remember to change the APP_KEY to your own. Lumen doesn’t offer a tool to generate it, so just smash the keyboard.

Create a migration file for the users table:

php artisan make:migration create_users_table

Modify the created file (for me that was database/migrations/2016_12_24_115448_create_users_table.php) to look like this:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

Modify database/factories/ModelFactory.php to look like this:

<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->email,
    ];
});

To create the seeder (it will populate your database with some users), modify database/seeds/UsersTableSeeder.php to look like:

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class)->create([
            'email' => 'user1@example.com',
            'password' => app('hash')->make('1234')
        ]);

        factory(App\User::class)->create([
            'email' => 'user2@example.com',
            'password' => app('hash')->make('1234')
        ]);

        factory(App\User::class)->create([
            'email' => 'user3@example.com',
            'password' => app('hash')->make('1234')
        ]);
    }
}

Important: You must now recreate the autoloader (Lumen still doesn’t know about the UsersTableSeeder class):

composer dump-autoload

Modify database/seeds/DatabaseSeeder.php to look like this:

<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $this->call(UsersTableSeeder::class);

        Model::reguard();
    }
}

Create database and populate it:

    touch database/database.sqlite
    php artisan migrate
    php artisan db:seed

You are now ready to integrate JWT into the project.

Integrate JWT

Add the JWT library to your project:

composer require tymon/jwt-auth:"1.0.0-beta.1"

Create a secret that will be used to generate tokens:

php artisan jwt:secret

To enable Middleware and Services related to Authentication/Authorization, uncomment or add these lines to bootstrap/app.php:

$app->withFacades();
$app->withEloquent();

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

$app->register(App\Providers\AuthServiceProvider::class);
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

Create a file to configure the Authentication service config/auth.php:

<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */
    'defaults' => [
        'guard' => env('AUTH_GUARD', 'api'),
        'passwords' => 'users',
    ],
    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */
    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],
    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    ],
    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],
];

Create a file to configure the JWT service config/jwt.php:

<?php

return [
    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Secret
    |--------------------------------------------------------------------------
    |
    | Don't forget to set this in your .env file, as it will be used to sign
    | your tokens. A helper command is provided for this:
    | `php artisan jwt:secret`
    |
    | Note: This will be used for Symmetric algorithms only (HMAC),
    | since RSA and ECDSA use a private/public key combo (See below).
    |
    */
    'secret' => env('JWT_SECRET'),

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Keys
    |--------------------------------------------------------------------------
    |
    | What algorithm you are using, will determine whether your tokens are
    | signed with a random string (defined in `JWT_SECRET`) or using the
    | following public & private keys.
    |
    | Symmetric Algorithms:
    | HS256, HS384 & HS512 will use `JWT_SECRET`.
    |
    | Asymmetric Algorithms:
    | RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
    |
    */
    'keys' => [
        /*
        |--------------------------------------------------------------------------
        | Public Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your public key.
        |
        | E.g. 'file://path/to/public/key'
        |
        */
        'public' => env('JWT_PUBLIC_KEY'),
        /*
        |--------------------------------------------------------------------------
        | Private Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your private key.
        |
        | E.g. 'file://path/to/private/key'
        |
        */
        'private' => env('JWT_PRIVATE_KEY'),
        /*
        |--------------------------------------------------------------------------
        | Passphrase
        |--------------------------------------------------------------------------
        |
        | The passphrase for your private key. Can be null if none set.
        |
        */
        'passphrase' => env('JWT_PASSPHRASE'),
    ],

    /*
    |--------------------------------------------------------------------------
    | JWT time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token will be valid for.
    | Defaults to 1 hour.
    |
    | You can also set this to null, to yield a never expiring token.
    | Some people may want this behaviour for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    |
    */
    'ttl' => env('JWT_TTL', 60),

    /*
    |--------------------------------------------------------------------------
    | Refresh time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token can be refreshed
    | within. I.E. The user can refresh their token within a 2 week window of
    | the original token being created until they must re-authenticate.
    | Defaults to 2 weeks.
    |
    | You can also set this to null, to yield an infinite refresh time.
    | Some may want this instead of never expiring tokens for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    |
    */
    'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),

    /*
    |--------------------------------------------------------------------------
    | JWT hashing algorithm
    |--------------------------------------------------------------------------
    |
    | Specify the hashing algorithm that will be used to sign the token.
    |
    | See here: https://github.com/namshi/jose/tree/master/src/Namshi/JOSE/Signer/OpenSSL
    | for possible values.
    |
    */
    'algo' => env('JWT_ALGO', 'HS256'),

    /*
    |--------------------------------------------------------------------------
    | Required Claims
    |--------------------------------------------------------------------------
    |
    | Specify the required claims that must exist in any token.
    | A TokenInvalidException will be thrown if any of these claims are not
    | present in the payload.
    |
    */
    'required_claims' => ['iss', 'iat', 'exp', 'nbf', 'sub', 'jti'],

    /*
    |--------------------------------------------------------------------------
    | Blacklist Enabled
    |--------------------------------------------------------------------------
    |
    | In order to invalidate tokens, you must have the blacklist enabled.
    | If you do not want or need this functionality, then set this to false.
    |
    */
    'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),

    /*
    | -------------------------------------------------------------------------
    | Blacklist Grace Period
    | -------------------------------------------------------------------------
    |
    | When multiple concurrent requests are made with the same JWT,
    | it is possible that some of them fail, due to token regeneration
    | on every request.
    |
    | Set grace period in seconds to prevent parallel request failure.
    |
    */
    'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),

    /*
    |--------------------------------------------------------------------------
    | Providers
    |--------------------------------------------------------------------------
    |
    | Specify the various providers used throughout the package.
    |
    */
    'providers' => [
        /*
        |--------------------------------------------------------------------------
        | JWT Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to create and decode the tokens.
        |
        */
        'jwt' => Tymon\JWTAuth\Providers\JWT\Namshi::class,
        /*
        |--------------------------------------------------------------------------
        | Authentication Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to authenticate users.
        |
        */
        'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,
        /*
        |--------------------------------------------------------------------------
        | Storage Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to store tokens in the blacklist.
        |
        */
        'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
    ],
];

Edit the boot() method in app/Providers/AuthServiceProvider.php to look like:

    public function boot()
    {
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

        $this->app['auth']->viaRequest('api', function ($request) {
            if ($request->input('email')) {
                return User::where('email', $request->input('email'))->first();
            }
        });
    }

Make app/User.php implement JWTSubject. It will look like:

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
    use Authenticatable, Authorizable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    /**
     * 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 [];
    }
}

All set up :) We just need to use it now. We will need:

  • Route to obtain the JWT token
  • A controller

First, create a route in app/Http/routes.php by adding:

$app->POST('/auth/login', 'AuthController@loginPost');

Now, create the controller by creating and editing app/Http/Controllers/AuthController.php to make it look like:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\JWTAuth;

class AuthController extends Controller
{
    /**
     * @var \Tymon\JWTAuth\JWTAuth
     */
    protected $jwt;

    public function __construct(JWTAuth $jwt)
    {
        $this->jwt = $jwt;
    }

    public function loginPost(Request $request)
    {
        $this->validate($request, [
            'email'    => 'required|email|max:255',
            'password' => 'required',
        ]);

        try {
            if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
                return response()->json(['user_not_found'], 404);
            }
        } catch (TokenExpiredException $e) {
            return response()->json(['token_expired'], $e->getStatusCode());
        } catch (TokenInvalidException $e) {
            return response()->json(['token_invalid'], $e->getStatusCode());
        } catch (JWTException $e) {
            return response()->json(['token_absent' => $e->getMessage()], $e->getStatusCode());
        }

        return response()->json(compact('token'));
    }
}

Now you are really completely ready. You just have to send email and password in a POST request to /auth/login. You can send them as form data, as part of a JSON object,… doesn’t mind.

For example:

curl -X POST -F 'email=user1@example.com' -F 'password=1234' http://localhost:8080/auth/login

The real life example

Now, the beauty of this integration with JWT is that you can just use the Authorization services provided by Lumen. The service will know that it has to use JWT, and you will keep using the “normal” interfaces.

So, you can follow the examples and techniques described in the Lumen documentation:

https://laravel.com/docs/5.3/authorization

To make it even clearer, I will complete this post with a real life example. The scenario:

  • User has posts
  • Anyone can see posts
  • Only Authenticated users can create posts
  • Only Owner can update a specific post

Create migration for posts table:

php artisan make:migration create_posts_table

Modify the created file (for me that was database/migrations/2016_12_24_225438_create_posts_table.php) to look like this:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('subject');
            $table->string('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }
}

Update the database with the new posts table:

php artisan migrate

Create the model for posts in ap/Post.php so it looks like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'subject', 'body',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [];

    /**
     * Get the user that owns the post.
     */
    public function post()
    {
        return $this->belongsTo(User::class);
    }
}

Modify the App/User.php to add the method:

    /**
     * Get the posts for the user.
     */
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

Modify app/Http/routes.php to add the routes to the methods we’ll use to handle posts:

$app->GET('/posts', 'PostController@index');
$app->POST('/posts', 'PostController@create');
$app->PUT('/posts/{postId}', 'PostController@update');

Create a controller for the new routes in app/Http/Controllers/PostController.php:

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Request;

class PostController extends Controller
{
    /**
     * Return whole list of posts<br>
     * No authorization required
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        return response()->json(Post::all());
    }

    /**
     * Create new post<br>
     * Only if the Posts' policy allows it
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function create()
    {
        $rules = array(
            'subject'   => 'required|string',
            'body'      => 'required|string',
        );
        $this->validate(Request::instance(), $rules);

        $this->authorize('create', Post::class);

        $post = new Post();
        $post->subject = Input::get('subject');
        $post->body = Input::get('body');
        Auth::user()->posts()->save($post);

        return response()->json($post);
    }

    /**
     * Update post<br>
     * Only if the Posts' policy allows it
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($post_id)
    {
        $rules = array(
            'subject'   => 'required|string',
            'body'      => 'required|string',
        );
        $this->validate(Request::instance(), $rules);

        $post = Post::find($post_id);
        $this->authorize('update', $post);

        try {
            $post->subject = Input::get('subject');
            $post->body = Input::get('body');
            $post->save();

            return response()->json($post);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Post not updated',
                'error' => $e->getMessage()
            ], 400);
        }
    }
}

In the controller, pay close attention to:

  • $this->authorize('create', Post::class); –> checks ‘create’, with no specific Post model
  • $this->authorize('update', $post); –> check ‘update’, for a specific model
  • Auth::user() –> gives us the currently Authenticated user

Now, we have to define those policies (‘create’ and ‘update’ for Posts) we just used.

Create app/Policies/PostPolicy.php with:

<?php

namespace App\Policies;

use App\Post;
use App\User;

class PostPolicy
{
    /**
     * Determine if the given user can create posts.
     *
     * @param  \App\User  $user
     * @return bool
     */
    public function create(User $user)
    {
        // As long as the user is real, allowed
        return $user->id != null;
    }

    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\User    $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(User $user, Post $post)
    {
        // Only if the user is the owner of the post
        return $user->id == $post->user_id;
    }
}

And at last, inform Lumen about your new Policy. To do so, edit the boot() method in app/Providers/AuthServiceProvider.php to look like:

    public function boot()
    {
        // Here you may define the policies will be applied

        Gate::policy(Post::class, PostPolicy::class);

        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

        $this->app['auth']->viaRequest('api', function ($request) {
            if ($request->input('email')) {
                return User::where('email', $request->input('email'))->first();
            }
        });
    }

You can now deploy and use:

  • POST /auth/login –> with email and password, obtain a JWT token
  • GET /posts –> anyone gets a list of all the posts in the database
  • POST /posts –> any authenticated user (using JWT, for instance) can create a post
  • PUT /posts/:post_id–> the Owner of :post_id (authenticated using JWT, for instance) can modify the post

And remember, JWT requires you to provide the token as a header. For example, let’s obtain a JWT token and use it to create a post (I leave further tests in your hands):

curl -X POST -F 'email=user1@example.com' -F 'password=1234' http://localhost:8080/auth/login

curl -X POST -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvdjEvYXV0aC9sb2dpbiIsImlhdCI6MTQ4MjYzNDE1MywiZXhwIjoxNDgyNjM3NzUzLCJuYmYiOjE0ODI2MzQxNTMsImp0aSI6IjJvaDRaNmFlS2xPRkRSSmQiLCJzdWIiOjF9.MJM6pFPdxLXu3uBxF8HIzEvjMPB5e-zg-DPgb3fcANs' -H 'Content-Type: application/json' -d '{"subject": "test subject", "body": "some text for the body"}' http://localhost:8080/posts
© 2017 Akaita development