Vue App with Lumen Passport API (Part I)
Tags: vue, lumen, laravel
Published: 2022-06-25 10:50:45

---
title: Vue App with Lumen Passport API (Part I)
published: true
description: 
tags: vue,lumen,laravel
cover_image: https://images.pexels.com/photos/4509131/pexels-photo-4509131.jpeg?auto=compress&cs=tinysrgb&w=1600
ratio: 100:42
# Use a ratio of 100:42 for best results.
---

## Why Lumen?
[Lumen](https://lumen.laravel.com/) is a stripped down version of [Laravel](https://laravel.com/) for building APIs. This makes it a lightweight framework. I'm currently using Lumen in a project and I want to use this opportunity to share some of the things I've learnt.

## What we'll build
We will build a Vue app for users to save their contacts. This will cover mainly authentication and CRUD operations. For the styling we'll use [Tailwindcss](https://tailwindcss.com/). For this Part I, we will be setting up lumen passport.

*Without further ado...*

## Create Lumen Project
Visit [Lumen](https://lumen.laravel.com/) and follow installation instruction.

## Install Lumen Generator
As pointed out earlier, a lot of things in Laravel are missing in Lumen. This package brings in some of Laravel artisan commands to Lumen. Run the following command in your terminal at the root of the project.

> composer require flipbox/lumen-generator

In bootstrap/app.php add the following:
```php
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);
```

Now we have some artisan commands. We can generate app key.
> php artisan key:generate

It's always good practice to use version control to keep track of your changes. 

You can also use [postman](https://www.postman.com/) to check that your endpoint is working.

## Install Lumen Passport
We'll be using a package by Dusterio. You can visit the Github link [here](https://github.com/dusterio/lumen-passport) to follow the installation or continue with the tutorial.
> composer require dusterio/lumen-passport

## Enable Laravel Passport and Lumen Passport
File path: bootstrap/app.php

Uncomment these lines to enable facade, eloquent and routeMiddleware
```php
$app->withFacades();

$app->withEloquent();

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

Uncomment the service providers as well
```php
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
$app->register(App\Providers\EventServiceProvider::class);
```

Register the Passport providers
```php
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
```

## Laravel Passport ^7.3.2 and newer
In bootastrap/app.php comment this out
```php
$app = new Laravel\Lumen\Application(
    dirname(__DIR__)
);
```

Use this instead
```php
$app = new \Dusterio\LumenPassport\Lumen7Application(
    dirname(__DIR__)
);
```

## Migrate and install Laravel Passport
### Create new tables for Passport in your database (eg. MySQL)
Create database and fill the details in .env
```php
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lumen_passport_blog
DB_USERNAME=root
DB_PASSWORD=root
```
> php artisan migrate

### Configure Authentication
Add the following to config/auth.php (You may have to create the config folder and auth.php file if they are not there)


```php
<?php
return [
    'defaults' => [
        'guards' => 'api'
    ],
    'guards' => [
        'api' => [
            'driver' => 'passport',
            'provider' => 'users', // default
        ],
    ],
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => \App\Models\User::class
        ]
    ],
];
```
Load the config since Lumen doesn't load config files automatically:
In bootstrap/app.php add the code below.
(Preferably below $app->configure(‘app’). Follow the pattern)
```php
$app->configure(‘auth’)
```

## Install encryption keys and other stuff for Passport
> php artisan passport:install

It will output the Personal access client ID and secret, and the Password grand client ID and secret. You may store these in your .env file or somewhere safe. Password grant client id and secret will be used for generating access token for user.

### Registering Routes
In app/Providers/AuthServiceProvider.php
Add the routes inside the boot method (preferably before any other code)
```php
use Dusterio\LumenPassport\LumenPassport;

LumenPassport::routes($this->app);
```

### User model
Add HasApiTokens trait to your user model.

```php
use Laravel\Passport\HasApiTokens;

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

    /* rest of the model */
}
```

Add ‘password’ to fillable array in user model.

### Create a user migration
> php artisan make:migration create_users_table

Modify migration table to add the fields: name, email and password. 
```php
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('email')->unique();
    $table->string('name');
    $table->string('password');
    $table->timestamps();
});
```
Then migrate.
> php artisan migrate

Finally, create a user with email and a hashed password. You will need this to generate a key. You can use tinker for this.

```
>>> use App\Models\User
>>> use Illuminate\Support\Facades\Hash
>>> User::create(['name'=>'John Doe', 'email'=>'johndoe@company.com', 'password'=>Hash::make('password')])
```

## Generate token with Postman
![Postman screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/javbzklaeh9j2nrrtwp4.png)
Open Postman and make a POST request to http://your_base_url/oauth/token. Enter the fields as in the image above. The username is the email of the user we created. Client secret and client id is the one we generated earlier. Be sure to make use of the correct password grant id and secret. 

When you send the request, access token will be generated. We did it! In part two, we will continue with registration and login.