快速开始lumen项目,集成passport+dingo,并解决跨域问题,统一返回数据格式,例子包含用户中心。

代码已放在 github 上,欢迎参考和提出 issue:lumen-quick-start github地址

快速开始

  • 安装包: composer install

  • 复制配置文件, 并修改配置: cp .env.example .env【数据库配置, passport配置】

  • 执行数据库迁移: php artisan migrate

  • 安装passport: php artisan passport:install

  • 启动项目: php -S localhost:8088 -t public/

  • 生成一条假用户数据: php artisan db:seed --class=UsersTableSeeder

从零开始构造介绍

项目初始化

  • 安装lumen安装器: composer global require "laravel/lumen-installer"

  • lumen new user-center 初始化一个项目 或者 composer create-project --prefer-dist laravel/lumen user-center

  • 执行 composer install 安装依赖包,如果是用 lumen new 命令可以省略这一步。

  • 复制配置文件 cp .env.example .env

  • 设置 APP_KEY 等配置信息, 因为 php artisan key:generate 没用

  • 启动项目 php -S localhost:8000 -t public

引入lumen-passport

  • 安装 lumen-passport#
composer require dusterio/lumen-passport
  • 修改 bootstrap/app.php 文件
// 集成passport
//只是取消注释
// 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);

// 自定义-下面有说到, 可以之后加
// 配置-新增
$app->configure('auth');

// 开启AppServiceProvider-取消注释
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);

// $app->alias('cache', 'Illuminate\Cache\CacheManager'); //新增,解决Lumen的Cache问题
  • 执行 migrate 和安装 passport
# Create new tables for Passport
php artisan migrate
# Install encryption keys and other necessary stuff for Passport
php artisan passport:install
$ 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
$ 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
  • 在根目录新建 config/auth.php 文件,加入以下内容
return [
    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],

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

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => \App\User::class
        ]
    ]
];
  • bootstrap/app.php 中引入配置文件
$app->configure('auth');
  • 注册路由

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);

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']);
  • 并且在 .env 文件中加入几项配置项
# 环境
APP_ENV=local
# 调试
APP_DEBUG=true
# 秘钥
APP_KEY=base64:24uriVnENMM+x8u8ouLsNlE4EohGNY1mxTGWdxmPt2w=
# 时区
APP_TIMEZONE=UTC
# 语言
#APP_LOCALE
# 数据库配置
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=user_center
DB_USERNAME=root
DB_PASSWORD=
# 缓存
CACHE_DRIVER=file
# 队列
QUEUE_DRIVER=sync
# passport password grant_type client(passport进行密码授权的客户端)
APP_CLIENT_ID=2
APP_CLIENT_SECRET=bohwT7qPxj8ltPUn21nDvmMVg5DYiRgoFCZYvVh7
# passport进行密码授权时请求路径,向自己请求
APP_URL=http://www.b.com

其他环境和配置准备

  • app 目录下添加通用函数文件 helper.php 并且通过文件的形式自动载入, 在 composer.json 里的 autoload 添加如下代码:
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/helpers.php"
        ]
    },
  • routes 文件下新建 api 路由文件夹, 并在 bootstrap\app.php 文件将它加载进来。
$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
    require __DIR__.'/../routes/web.php';
    require __DIR__.'/../routes/api/v1.php';
});
  • 安装 dingo#
composer require dingo/api:1.0.x@dev

lumen 5.5 使用下面命令

"require": {
    "dingo/api": "2.0.0-alpha1"
}
  • dingo 引入到 lumen

bootstrap/app.php 文件中引入:

$app->register(Dingo\Api\Provider\LumenServiceProvider::class);
  • app 目录下新增 ModelsSerializersTransformers 目录,dingo 返回数据的时候可以 transform

  • 配置自定义配置文件

你还可以创建自定义的配置文件并使用 $app->configure() 方法来加载它们。例如,如果你的配置文件位于config/options.php,你可以像这样加载它:$app->configure('options');

  • 为了刷新 token 还可以引入 Listeners

  • 引入所有的 config

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

通过 passport 进行鉴权

  • 为了将 Unauthorized. 以状态码加提示信息的形式返回。在 Exceptions\Handler.php 目录的 render函数中加入
        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);
        }

解决跨域问题lumen-cors【现在换成了用laravel-cors#

// laravel-cors
composer require barryvdh/laravel-cors

bootstrap/app.php 文件中

// laravel-cors
// 注册 `cors` 的服务提供者
$app->register(Barryvdh\Cors\ServiceProvider::class);

$app->routeMiddleware([
    'cors' => \Barryvdh\Cors\HandleCors::class,
]);
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容