The code has been put on Github, welcome to reference and propose the issue: lumen-quick-start Github address

Quick start

  • Installation package: Composer Install

  • Copy the configuration file and change the configuration: cp.env.example. env

  • Run the PHP artisan Migrate database

  • Passport: PHP Artisan Passport: Install

  • PHP -s localhost:8088 -t public/

  • PHP artisan DB :seed –class=UsersTableSeeder

Structure introduction from scratch

Project initialization

  • Composer global require “Laravel/lumen-Installer”

  • Initialize a project with lumen new user-center or composer create-project –prefer-dist Laravel /lumen user-center

  • Run composer install to install dependencies. You can skip this step if you use lumen new.

  • Copy the configuration file cp.env.example. env

  • Set configuration information such as APP_KEY, because PHP artisan key:generate is useless

  • PHP -s localhost:8000 -t public

Introducing lumen – passport

  • The installationlumen-passport 包 #
composer require dusterio/lumen-passport
Copy the code
  • Modify thebootstrap/app.phpfile
// Integrate passport // just uncomment // 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); // customize - add // config - add$app->configure('auth'); // Start AppServiceProvider. - Uncomment AppServiceProvider$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);

// $app->alias('cache'.'Illuminate\Cache\CacheManager'); // Add the Lumen Cache to solve the problemCopy the code
  • performmigrateAnd installationpassport
# Create new tables for Passport
php artisan migrate
# Install encryption keys and other necessary stuff for Passport
php artisan passport:install
Copy the code
$ php artisan migrate
Migration table created successfully.
Migrating: 2016_06_01_000001_create_oauth_auth_codes_table
Migrated:  2016_06_01_000001_create_oauth_auth_codes_table
Migrating: 2016_06_01_000002_create_oauth_access_tokens_table
Migrated:  2016_06_01_000002_create_oauth_access_tokens_table
Migrating: 2016_06_01_000003_create_oauth_refresh_tokens_table
Migrated:  2016_06_01_000003_create_oauth_refresh_tokens_table
Migrating: 2016_06_01_000004_create_oauth_clients_table
Migrated:  2016_06_01_000004_create_oauth_clients_table
Migrating: 2016_06_01_000005_create_oauth_personal_access_clients_table
Migrated:  2016_06_01_000005_create_oauth_personal_access_clients_table
Copy the code
$ php artisan passport:install
Encryption keys generated successfully.
Personal access client created successfully.
Client ID: 1
Client Secret: oIWaBwhNt2KZD606lb0Il5dZl8D72fhMBUwkPvHW
Password grant client created successfully.
Client ID: 2
Client Secret: gvpDe6KIieDD1dvouk639fsxD6wLiNjbPuabT4wh
Copy the code
  • Create a new directory in the root directoryconfig/auth.phpFile, add the following
return [
    'defaults'= > ['guard'= >'api'.'passwords'= >'users',].'guards'= > ['api'= > ['driver'= >'passport'.'provider'= >'users',]],'providers'= > ['users'= > ['driver'= >'eloquent'.'model' => \App\User::class
        ]
    ]
];
Copy the code
  • inbootstrap/app.phpTo import configuration files
$app->configure('auth');
Copy the code
  • Registered routing

Next, you should call the LumenPassport::routes method within the boot method of your application (one of your service providers). This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

Dusterio\LumenPassport\LumenPassport::routes($this->app);
Copy the code

You can add that into an existing group, or add use this route registrar independently like so;

Dusterio\LumenPassport\LumenPassport::routes($this->app, ['prefix'= >'v1/oauth']);
Copy the code
  • And in the.envAdd several configuration items to the file
# environment
APP_ENV=local
# debugging
APP_DEBUG=true
# the secret key
APP_KEY=base64:24uriVnENMM+x8u8ouLsNlE4EohGNY1mxTGWdxmPt2w=
# time zone
APP_TIMEZONE=UTC
# language
#APP_LOCALE
# database configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=user_center
DB_USERNAME=root
DB_PASSWORD=
# cache
CACHE_DRIVER=file
# queue
QUEUE_DRIVER=sync
# passport password grant_type client
APP_CLIENT_ID=2
APP_CLIENT_SECRET=bohwT7qPxj8ltPUn21nDvmMVg5DYiRgoFCZYvVh7
# passport request path when requesting password authorization
APP_URL=http://www.b.com
Copy the code

Other environment and configuration preparations

  • inappAdd generic function files to directoryhelper.phpAnd automatically load it in the form of a filecomposer.jsonIn theautoloadAdd the following code:
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/helpers.php"]},Copy the code
  • inroutesNew Under FileapiRoute folder and inbootstrap\app.phpThe file loads it in.
$app->group(['namespace'= >'App\Http\Controllers'].function ($app) {
    require __DIR__.'/.. /routes/web.php';
    require __DIR__.'/.. /routes/api/v1.php';
});
Copy the code
  • The installationdingo 包 #
Composer require dingo/API: 1.0 x @ devCopy the code

Lumen 5.5 Use the following command

"require": {
    "dingo/api": "2.0.0-1"
}
Copy the code
  • willdingoIntroduced to thelumen

In the bootstrap/app.php file:

$app->register(Dingo\Api\Provider\LumenServiceProvider::class);
Copy the code
  • Add Models, Serializers, and Transformers directories under app, and transform when dingo returns data

  • Configure a custom configuration file

You can also create custom configuration files and load them using the $app->configure() method. For example, if your configuration file is located in config/options.php, you can load it like this: $app->configure(‘options’);

  • Listeners can also be introduced to refresh tokens

  • Import all config

// config
$app->configure('app');
$app->configure('auth');
$app->configure('secrets');
$app->configure('filesystems');
Copy the code

throughpassportFor authentication

  • In order toUnauthorized.A status code and prompt message are displayed. inExceptions\Handler.phpThe directoryrenderAdd to the function
        switch (true) {
            case $e instanceof AuthorizationException:
                return response('This action is unauthorized.', 403);
            case $e instanceof ModelNotFoundException:
                return response('The model is not found.', 404);
        }
Copy the code

Resolve cross-domain problemslumen-corsNow laravel-Cors is used instead#】

// laravel-cors
composer require barryvdh/laravel-cors
Copy the code

In the bootstrap/app.php file

// register the service provider of 'CORS'$app->register(Barryvdh\Cors\ServiceProvider::class);

$app->routeMiddleware([
    'cors' => \Barryvdh\Cors\HandleCors::class,
]);
Copy the code