ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
1、安装 jwt-auth。 ``` composer require tymon/jwt-auth 1.*@rc ``` 2.在config/app.php中注册服务提供者。 ``` 'providers' => [ Tymon\JWTAuth\Providers\LaravelServiceProvider::class, ] ``` 3.生成配置文件。 ``` php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" ``` 此命令会在config目录下生成一个jwt.php配置文件 4.生成密钥。 ``` php artisan jwt:secret ``` 5.在config/auth.php文件中,添加guard和Providers,代码如下。 ``` 'auth_admin' => [ 'driver' => 'jwt', 'provider' => 'auth_admins' ], 'auth_admins' => [ 'driver' => 'eloquent', 'model' => Modules\AuthAdmin\Models\AuthAdmin::class, ], ``` 6.构建模型层。 ``` <?php namespace Modules\AuthAdmin\Models; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Modules\AuthAdmin\Services\AuthAdminService; use Modules\AuthAdmin\Models\BaseApiModel; class AuthAdmin extends Authenticatable implements JWTSubject { use Notifiable; protected $guard = 'auth_admin'; protected $hidden = [ 'password' ]; /** * @name jwt标识 */ public function getJWTIdentifier() { return $this->getKey(); } /** * @name jwt自定义声明 */ public function getJWTCustomClaims() { return []; } /** * @name 用户登录 */ public function login($data){ $BaseApiModel = new BaseApiModel(); if (true == \Auth::guard('auth_admin')->attempt($data)) { $user_info = $this->where(['username'=>$data['username']])->select('id','username')->first(); if($user_info){ $user_info = $user_info->toArray(); $user_info['password'] = $data['password']; $token = (new AuthAdminService())->set_token($user_info); if(count($token)){ return $BaseApiModel->api_success([ 'msg'=>'登录成功!', 'data'=>$token ]); } return $BaseApiModel->api_error(['msg'=>'登录失败!']); } } return $BaseApiModel->api_error(['msg'=>'账号或密码错误!']); } } ``` 7.创建权限验证中间件。 ``` <?php namespace Modules\AuthAdmin\Http\Middleware; use Closure; use Illuminate\Http\Request; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; use Tymon\JWTAuth\Exceptions\TokenInvalidException; use JWTAuth; use Modules\AuthAdmin\Models\Admin as AdminModel; class AdminApiAuth { /** * Handle an incoming request. * php artisan module:make-middleware AdminAuth Admin * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { $route_data = $request->route(); $url = str_replace($route_data->getAction()['prefix'] . '/',"",$route_data->uri); $url_arr = ['auth/login/login']; $response = $next($request); $api_key = $request->header('apikey'); if($api_key != config('authadmin.api_key')){ return response()->json([ 'code' => 1101, 'msg'=>'apikey错误!' ],401); } if(in_array($url,$url_arr)){ return $response; } try { if (! $user = JWTAuth::parseToken()->authenticate()) { //获取到用户数据,并赋值给$user return response()->json([ 'code' => 1004, //'msg' => '用户不存在' 'msg'=>'请先登录!' ],400); } return $response; } catch (TokenExpiredException $e) { return response()->json([ 'code' => 1003, 'msg' => 'token 过期' , //token已过期 ],400); } catch (TokenInvalidException $e) { if(in_array($url,['auth/auth/refresh',])){ return $response; }else{ return response()->json([ 'code' => 1002, //'msg' => 'token 无效', //token无效 'msg'=>'请先登录!' ],400); } } catch (JWTException $e) { return response()->json([ 'code' => 1001, //'msg' => '缺少token' , //token为空 'msg'=>'请先登录!' ],400); } } } ``` 8.创建jwt的Services服务。 ``` <?php namespace Modules\AuthAdmin\Services; use Tymon\JWTAuth\Facades\JWTAuth; class AuthAdminService { public function __construct() { \Config::set('auth.defaults.guard', 'auth_admin'); } /** * @name 设置token */ public function set_token($data){ if (! $token = JWTAuth::attempt($data)){ return []; } return $this->respond_with_token($token); } /** * @name 我的信息 */ public function my(){ return JWTAuth::parseToken()->touser(); } /** * @name 退出登录 */ public function logout() { return JWTAuth::parseToken()->invalidate(); } /** * @name 刷新 */ public function refresh() { return $this->respond_with_token(JWTAuth::parseToken()->refresh()); } /** * @name 组合token数据 */ protected function respond_with_token($token) { return [ 'token' => $token, 'token_type' => 'bearer', 'expires_in' => JWTAuth::factory()->getTTL() * 60 ]; } } ``` 视频链接 ```[youku] XNDU0NzI3ODYyOA ```