lumen7+jwt相对正确的使用方式

前言

当前官方Lumen最新版本:7.1.3
项目根目录:/home/wwwroot/blog
项目域名:api.kimphp.com

安装JWT

composer require tymon/jwt-auth

修改app.php及AppServiceProvider.php

编辑blog/bootstrap/app.php
取消以下代码注释:
.

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

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

编辑blog/app/Providers/AppServiceProvider.php
在register方法内添加:

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

如下图:
在这里插入图片描述

配置env

添加配置项

编辑blog/.env
添加如下配置:

#JWT身份验证密钥,添加完配置后,执行以下命令php artisan jwt:secret将会自动获取JWT身份验证密钥并会自动填充
JWT_SECRET=
#JWT公钥,也可以是JWT公钥文件所在路径
JWT_PUBLIC_KEY=
#JWT私钥,也可以是JWT私钥文件所在路径
JWT_PRIVATE_KEY=
#JWT密码短语,也就是密码,如果不设置,留空即可
JWT_PASSPHRASE=
#JWT令牌有效时长(分钟),默认60分钟,留空则代表令牌永不过期,如果留空则必须从required_claims中移除exp
JWT_TTL=60
#指定JWT令牌刷新的有效时长(分钟),默认2周,留空则代表令牌获得无限刷新时间
JWT_REFRESH_TTL=20160
#JWT签名令牌的哈希算法
JWT_ALGO=HS256
#指定JWT令牌验证期间允许的时间偏差秒数,适用于(`iat`、`nbf`、`exp`)这三种断言,默认是0
JWT_LEEWAY=0
#启用黑名单,要使令牌失效,必须启用黑名单。如果不希望或不需要此功能,请将其设置为false。
JWT_BLACKLIST_ENABLED=true
#黑名单宽限期,当用同一个JWT发出多个并发请求时,由于每一个请求都会再生令牌,其中一些可能会失败,以秒为单位设置宽限期以防止并行请求失败。
JWT_BLACKLIST_GRACE_PERIOD=0

如下图:
在这里插入图片描述

生成JWT_SECRET

执行以下命令,将会自动获取JWT身份验证密钥并会自动填充到.env对应配置中

php artisan jwt:secret

增加auth.php配置并编辑

复制blog\vendor\laravel\lumen-framework\config\auth.phpblog\config\auth.php
修改blog\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'),
    ],

    /*
    |--------------------------------------------------------------------------
    | 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: "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
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You may also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | 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' => [
        //
    ],
];

增加登录控制器AuthController.php

纯lumen下AuthController.php示例

新建blog\app\Http\Controllers\AuthController.php
代码如下:

<?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
{
    protected $jwt;

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

    public function login(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'));
    }
}

lumen+dingo/api下AuthController.php示例

新建blog\app\Http\Controllers\v1\AuthController.php
代码如下:

<?php

namespace App\Http\Controllers\v1;

use App\Http\Controllers\Controller;
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
{
    protected $jwt;

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

    public function login(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'));
    }
}

增加路由

纯lumen下路由示例

<?php
$router->post('auth/login', 'AuthController@login');

lumen+dingo/api下路由示例

<?php
$api = app('Dingo\Api\Routing\Router');
/** @var Dingo\Api\Routing\Router $api */
$api->version('v1', ['namespace' => 'App\Http\Controllers\v1'],function ($api) {
    /** @var Dingo\Api\Routing\Router $api */
    $api->post('auth/login', 'AuthController@login');
    $api->get('hello_world','HelloWorldController@index');
});

测试

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章