Integrating Laravel Passport in Your Lumen Project (with example)
A Detailed Guide On How To Integrate Laravel Passport in Lumen
Lumen, as we already know is a micro-framework by Laravel well suited for developing micro-services and APIs.
However, setting up Passport in Lumen for authentication has been a bit of a challenge for most developers as Passport doesn’t have an actual support for Lumen despite being built by the same developer of the Laravel framework, Taylor Otwell.
To fix this, Denis Mysenko helped with a workaround by developing ‘lumen-passport’, a simple provider that makes Laravel passport work with Lumen.
How do we get this working? Let’s get started!
Let’s assume we’re working with a new project called “blog”.
- Install and set up Lumen:
composer create-project --prefer-dist laravel/lumen blog
Set up your env file by running:
cp .env.example .env
Then edit the .env file to point to your database appropriately and also generate your APP_KEY.
DB_DATABASE=blog_dbDB_USERNAME=rootDB_PASSWORD=*******
2. Install Lumen Passport
composer require dusterio/lumen-passport
Next, according to the docs, open your bootstrap/app.php file and modify as below:
// Enable Facades
$app->withFacades();// Enable Eloquent
$app->withEloquent();...// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);...// Finally register two service providers - original one and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
What we are doing here is enable the enable both the $app->withFacades() and $app->withEloquent() methods. Also, we need to enable the ‘auth’ middleware since we’re dealing with authentications here.
Lastly, we add the two (2) Service providers shipped with the Lumen Passport package.
3. Next, migrate and install Laravel Passport
# Create new tables for Passport
php artisan migrate# Install encryption keys and other necessary stuff for Passport
php artisan passport:install
Once you run php artisan passport:install a client secret and token would be generated and saved in your database. Kindly take note of it as it would be used for logging users in.
4. Afterwards, create a “config” directory in the project’s root (if it doesn’t exist) and create a auth.php file inside it.
<?phpreturn [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\User::class
]
]
];
Next, load the config in bootstrap/app.php
since Lumen doesn't load config files automatically:
$app->configure('auth');
5. Set the routes as below in the same bootstrap/app file.
\Dusterio\LumenPassport\LumenPassport::routes($app, ['prefix' => 'v1/oauth']);
6. Navigate to your app/User.php model file. Ensure the model uses Passport’s HasApiTokens trait. E.g.
use Laravel\Passport\HasApiTokens;...class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use HasApiTokens, Authenticatable, Authorizable;/* rest of the model */
}
Also, update the $fillable array by adding the ‘password’ field.
protected $fillable = [
'name', 'email', 'password'
];
That’s pretty much about it!
Congrats, you have successfully configured Passport on your Lumen project.😀😀😀😀
But don’t rejoice just yet. Let’s try and use for a simple user authentication process to be sure it all works out well.
Create a UsersController.php file
Define your user registration route in your /routes/web.php file:
$router->post('/register','UsersController@register');
Create your Users table migration and define your schema as below:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email');
$table->string('password');
$table->timestamp('last_logged_in')->nullable();
$table->timestamps();
});
Run php artisan migrate immediately after.
Now it’s time to run actual tests:
Open your Postman and enter required parameters:
Here’s my sample response:
Congrats! You’ve been able to successfully sign up your first user.
Now, how do your users sign in?
Remember we added a route to our bootstrap/app/php file?
Now, open your Postman and use the /v1/oauth/token endpoint and use the sample POST request data as in the screenshot below:
To retrieve your ‘client_secret’, kindly access the oauth_clients table in your local database and copy the secret of your Password Grant Client. Set the ‘client_id’ of your request as the id (e.g. 2) of that same record just as in the screenshot above.
Below is the response of our sent request.
To process any request for the authenticated user, always add to your request’s header an Authorization key with Bearer {access_token} as the value.
The value of the {access_token} can be retrieved from the response gotten from the login response data.
Thank you!!
PS: This is my first article ever. Reviews would be indeed appreciated.