当前位置: 首页 > 后端技术 > PHP

Laravel使用JWT做API认证

时间:2023-03-29 17:05:13 PHP

最近项目在做API认证。最终的技术选择决定使用JWT。项目框架使用laravel。Laravel使用了JWT,并且有一个更方便的开源包:jwt-auth。使用composer安装jwt-auth,laravel使用的框架版本是5.0,jwt-auth最新稳定版是0.5.12。(最新版本为1.0.*,需要laravel5.4或以上版本)composerrequiretymon/jwt-auth0.5.*安装完成后,需要在config/app.php中注册对应的服务提供者:'providers'=>['Tymon\JWTAuth\Providers\JWTAuthServiceProvider',],然后注册对应需要使用的门面:'aliases'=>['JWTAuth'=>'Tymon\JWTAuth\Facades\JWTAuth','JWTFactory'=>'Tymon\JWTAuth\Facades\JWTFactory',],然后发布对应的配置文件:该命令会在config目录下生成一个jwt.php配置文件,您可以在其中自定义配置。phpartisanvendor:publish--provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"最后生成一个key:这个命令会新增一行JWT_SECRET=secretphpartisanjwt:generate在你的.env文件中生成一个TOKEN,有多少个token生成方法一种:下面介绍两种方法。1、根据模型生成TOKEN:根据模型生成TOKEN,需要在config/auth.php中指定使用哪种模型。'model'=>'App\Models\Members',需要在模型文件Members中添加namespaceApp\Models;useIlluminate\Database\Eloquent\Model;useIlluminate\Auth\Authenticatable;useIlluminate\Contracts\Auth\.phpAuthenticatableasAuthenticatableContract;classMembersextendsModelimplementsAuthenticatableContract{使用Authenticatable;...}根据模型生成TOKEN$member=\App\Models\Members::where('id',7)->select('id','username')->first();$token=\JWTAuth::fromUser($member);echo$token;exit;二、自定义生成TOKEN:$customClaims=['sub'=>['id'=>'7','name'=>'kocor',]];$payload=\JWTFactory::make($customClaims);$token=\JWTAuth::encode($payload);echo$token;exit;解密提取TOKEN信息提取TOKEN信息$user_info=JWTAuth::parseToken()->authenticate()刷新令牌$newToken=JWTAuth::refresh($_REQUEST['token']);例子useTymon\JWTAuth\Exceptions\JWTException;useTymon\JWTAuth\Exceptions\TokenExpiredException;useTymon\JWTAuth\Exceptions\TokenInvalidException;//JWT提取成员信息试试{if(!$user_info=JWTAuth::parseToken()->authenticate()){returnApi::arr(config('statusCode.jwt_user_not_found'),trans('message.jwt_user_not_found').':404');}//token有效期内允许刷新$newToken=JWTAuth::refresh($_REQUEST['token']);returnApi::json(config('statusCode.success'),trans('message.success'),$newToken);}catch(TokenExpiredException$e){try{//刷新有效期内$newToken=JWTAuth::refresh($_REQUEST['token']);返回Api::json(config('statusCode.success'),trans('message.success'),$newToken);}catch(JWTException$e){//过期用户returnApi::json(config('statusCode.jwt_token_expired'),trans('message.jwt_token_expired').$e->getStatusCode());}//无效的标记不存在}catch(JWTException$e){returnApi::json(config('statusCode.jwt_token_absent'),trans('message.jwt_token_absent').$e->getStatusCode());}作者:kocor