lumen使用jwt(一)

使用的是 lumen5.3.*
做api接口,第一步就是需要实现身份验证,(dingo-api没搞懂) 选择常规的 jwt

本文参考https://www.jianshu.com/p/cbf582ec5c7f

1. 安装引入 jwt

composer require tymon/jwt-auth

速度慢的尝试切换阿里云镜像再执行(安装lumen应该已经配置过了)

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ 

2. config 目录下新建一个 auth.php 文件

Lumen 项目中,默认没有 config 文件夹,需要在项目根目录创建,并将 vendor 源代码中auth.php 复制出来,同时将 api 认证指定为 「jwt」

  • auth.php参考:
 [
        '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: "session", "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' => [
        //
    ],

];
  • 然后在 /Providers/AppServiceProvider.php 中注册 LumenServiceProvider:
$this->app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class);
  • jwt需要生成secret,执行后会生成在.env文件中,
php artisan jwt:secret
  • 你可以接着.env里配置默认的过期时间等参数
JWT_SECRET=Vd7Qnv0*******************BZ6rYUeQIa39j
//有效时间 单位:分钟
JWT_TTL = 60
//刷新时间  单位:分钟  默认 14天 
JWT_REFRESH_TTL = 20160
//宽限时间 单位:秒
JWT_BLACKLIST_GRACE_PERIOD = 60

3. 在bootstrap/app.php打开其中的中间件配置 withFacades

并增加auth中间件
参考:

load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/
$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);
$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);
$app->configure('pay');
$app->configure('wechat');
$app->configure('message');
/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/
 $app->middleware([
    App\Http\Middleware\ExampleMiddleware::class,
    App\Http\Middleware\CrossHttp::class
 ]);
//让数据库信息和认证服务修改生效
$app->withFacades();
$app->withEloquent();
//认证中间件
$app->routeMiddleware([
    'authToken' => App\Http\Middleware\AuthToken::class,
    'adminToken' => App\Http\Middleware\AuthAdminToken::class,
// // 增加 auth 中间件
 'auth' => App\Http\Middleware\Authenticate::class,
]);

//开启注册提供者
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
$app->register(Illuminate\Redis\RedisServiceProvider::class);
$app->register(SimpleSoftwareIO\QrCode\QrCodeServiceProvider::class);
$app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class);
//注册dingo/jwt


$app->alias('QrCode', 'SimpleSoftwareIO\QrCode\QrCodeServiceProvider');




/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

// $app->register(App\Providers\AppServiceProvider::class);
// $app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
    require __DIR__.'/../routes/web.php';
    require __DIR__.'/../routes/admin.php';
});
return $app;


. 修改**app/app.php **,继承参考,

默认是user 会查询其复数形式users,需要修改默认表的,参考修改变量 $table

getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

5. 建立好用户表,测试下登录

用户密码字段 必须必须必须password
且是hash加密的,(..)
且必须有id字段,验证查找用,(主要是目前没找到在哪改主键)

  • 设置下登录路由
    参考
post('/auth/login', 'AuthController@postLogin');

  • 登录参考
jwt = $jwt;
    }

    public function postLogin(Request $request)
    {
        if (! $token = $this->jwt->attempt($request->only('phone', 'password'))) {
            return response()->json(['user_not_found'], 404);
        }

        return response()->json(compact('token'));
    }
}

  • 获取到token
    image.png

6. AuthController 中增加中间件验证

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

        $this->middleware('auth:api', ['only' => ['getinfo']]);
    }
  • 或者路由中增加中间件验证,
// 使用 auth:api 中间件
$app->group(['middleware' => 'auth:api'], function($app) use ($route)
{ 
    $app->post('getinfo','AuthController@getinfo');
});
  • 把token带上post下试试,获取用户信息,默认参数名 :Authorization
    image.png

    一个小坑 这里post软件我放header里Authorization不行,前端应该可以,

你可能感兴趣的:(lumen使用jwt(一))