背景:正在测试使用lumen做接口开发,由于http是无状态的,需要对每次进行请求的用户进行身份验证,采用了jwt-token的方式进行验证
poser require tymon/jwt-auth:"1.0.0-rc.4"
生成jwt secret key
php artisan jwt:secret
bootstrap();
$app = new Laravel\Lumen\Application(
dirname(__DIR__)
);
$app->withFacades();
$app->withEloquent();
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
// $app->middleware([
// App\Http\Middleware\ExampleMiddleware::class
// ]);
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
// $app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
$app->router->group([
'namespace' => 'App\Http\Controllers',
], function ($router) {
require __DIR__.'/../routes/web.php';
});
return $app;
将vendor\laravel\lumen-framework\config\app.php复制一份放在根目录的config文件夹中,并进行修改
[
'guard' => env('AUTH_GUARD', 'api'),
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users'
]
],
'providers' => [
//
'users' => [
'driver' => 'eloquent',
'model' => \App\models\UserModel::class,
]
],
'passwords' => [
//
],
];
public function boot()
{
$this->app['auth']->viaRequest('api', function ($request) {
return app('auth')->setRequest($request)->user();
});
}
我在app文件夹下新建了models文件夹,创建了UserModel.php
getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
表的结构
where('username', '=', $request->input('username'))
->where('password', '=', sha1($this->salt . $request->input('password')))
->first();
if ($user_info) {
if (!$token = Auth::login($user_info)) {
$response['code'] = '5000';
$response['errorMsg'] = '系统错误,无法生成令牌';
} else {
$response['data']['user_id'] = strval($user_info->id);
$response['data']['access_token'] = $token;
$response['data']['expires_in'] = strval(time() + 86400);
}
} else {
$response['code'] = '5002';
$response['msg'] = '无法响应请求,服务端异常';
}
return response()->json($response);
}
public function test()
{
var_dump(Auth::user()->id);
}
}
$router->post('user/postLogin', 'AuthController@postLogin');
$router->group(['prefix'=>'jwt', 'middleware'=>'auth'], function() use ($router){
$router->get('test', 'AuthController@test');
});
参考文章(谢谢):
https://blog.csdn.net/daily886/article/details/81386668
https://blog.csdn.net/u012946588/article/details/79104885