lumen使用jwt做接口验证

    xiaoxiao2022-07-03  122

    背景:正在测试使用lumen做接口开发,由于http是无状态的,需要对每次进行请求的用户进行身份验证,采用了jwt-token的方式进行验证

    安装lumen(来自lumen文档。。懒了)

    安装jwt(github)

    poser require tymon/jwt-auth:"1.0.0-rc.4"

    生成jwt secret key

    php artisan jwt:secret

    修改bootstrap/app.php

    <?php require_once __DIR__.'/../vendor/autoload.php'; (new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables( dirname(__DIR__) ))->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;

    在根目录下新建config文件夹(laravel自带)

    将vendor\laravel\lumen-framework\config\app.php复制一份放在根目录的config文件夹中,并进行修改

    <?php return [ 'defaults' => [ 'guard' => env('AUTH_GUARD', 'api'), 'passwords' => 'users', ], 'guards' => [ 'api' => [ 'driver' => 'jwt', 'provider' => 'users' ] ], 'providers' => [ // 'users' => [ 'driver' => 'eloquent', 'model' => \App\models\UserModel::class, ] ], 'passwords' => [ // ], ];

    修改app\Providers\AuthServiceProvider.php

    public function boot() { $this->app['auth']->viaRequest('api', function ($request) { return app('auth')->setRequest($request)->user(); }); }

    创建模型

    我在app文件夹下新建了models文件夹,创建了UserModel.php

    <?php namespace App\models; use Illuminate\Auth\Authenticatable; use Laravel\Lumen\Auth\Authorizable; use Illuminate\Database\Eloquent\Model; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Tymon\JWTAuth\Contracts\JWTSubject; class UserModel extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject { use Authenticatable, Authorizable; protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'username', 'email', 'password', 'api_token' ]; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = [ 'password', ]; public function getJWTIdentifier() { return $this->getKey(); } public function getJWTCustomClaims() { return []; } }

    表的结构

    在Controllers新建AuthController.php

    <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\models\UserModel; class AuthController extends Controller { private $salt = 'it`s hard to guess'; public function postLogin(Request $request) { $user_model = new UserModel(); $user_info = $user_model->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

    最新回复(0)