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

laravel5.4+dingoapi+jwtinsteadofPassport

时间:2023-03-30 05:50:31 PHP

前言因为在度娘里找了半天,一大堆抄袭的版本,害死我了。我在每个问题上都尝试了很多问题。你做完后总结了吗?一次?然后有几个用lunmen+dingoapi+jwt,根本不行,太监版不是我要的。后来谷歌终于找到例子,测试成功。直接安装一个新的LVcomposercreate-project--prefer-distlaravel/laravelmyApiProjectinstalldingoapi添加composerrequiredingo/api:1.0.x@devinconfig/app.php'providers'=>[//很多Dingo\Api\Provider\LaravelServiceProvider::class在前面,】发布配置文件终端运行phpartisanvendor:publish--provider="Dingo\Api\Provider\LaravelServiceProvider"打开.env文件,放上dingo的配置在API_STANDARDS_TREE=vnd末尾//环境API_SUBTYPE=myapp//子类型API_PREFIX=api//前缀API_DOMAIN=api.myapp.com//子域名(前缀和子域名只能存在一个)optionalAPI_VERSION=v1//版本API_NAME=MyAPI//名称(使用API??Blueprint命令)API_CONDITIONAL_REQUEST=false//条件请求API_STRICT=false//严格模式API_DEFAULT_FORMAT=json//响应格式API_DEBUG=true//以下是我在debug模式下的配置:API_STANDARDS_TREE=vndAPI_SUBTYPE=emallAPI_PREFIX=apiAPI_VERSION=v1不是需要每一个都匹配,主要的安装jwt或者composer.json就够了"require-dev":{"tymon/jwt-auth":"1.0.*"},"minimum-stability":"dev","prefer-stable":true其实你加就行了,下面是我的写法,上面是国外的写法"tymon/jwt-auth":"1.0.*@dev"运行composerupdate安装dingo和jwt添加jwtconfig/api.php中的身份验证添加内容'auth'=>['jwt'=>Dingo\Api\Auth\Provider\JWT::class]inconfig/app.php'providers'=>[//frontA很多Tymon\JWTAuth\Providers\LaravelServiceProvider::class],'aliases'=>[//前面很多'JWTAuth'=>Tymon\JWTAuth\Facades\JWTAuth::class]在终端运行:phpartisanvendor:publish--provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"会生成config/jwt.php这个是jwt配置文件生成.env文件的jwt密钥运行:phpartisanjwt:secretroutingsrouters中的新内容/api.php,注册和登录两条路径://这句话接管路由$api=app('Dingo\Api\Routing\Router');$api->version('v1',function($api){$api->post('login','App\Http\Controllers\Api\Auth\LoginController@login');$api->post('注册','App\Http\Controllers\Api\Auth\RegisterController@register');});生成两个控制器终端输入:phpartisanmake:controllerApp\\Http\\Api\\Auth\\LoginControllerphpartisanmake:controllerApp\\Http\\Api\\Auth\\RegisterController数据库准备。环境文件DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=databasenameDB_USERNAME=rootDB_PASSWORD=添加迁移文件,当然你也可以使用phpartisanmake:auth来安装LV自带的用户我们使用新建的终端运行:phpartisanmake:modelUser-m这个命令可以添加迁移文件同时添加模型迁移文件。一般打开database/migrations/timeformat_create_users_table.php中的迁移文件,修改如下内容:publicfunctionup(){Schema::create('users',function(Blueprint$table){$table->increments('id');$table->string('name')->unique();$table->string('email')->unique();$table->string('password');$table->rememberToken();$table->timestamps();});}终端操作:phpartisanmigrate创建用户表打开我们新建的Model在App/下的User.php中添加如下内容:useIlluminate\Notifications\Notifiable;useIlluminate\Foundation\Auth\UserasAuthenticatable;useTymon\JWTAuth\Contracts\JWTSubject;classUserextendsAuthenticatableimplementsJWTSubject{使用Notifiable;/***可批量分配的属性。**@var数组*/protected$fillable=['name','email','密码',];/***应该为数组隐藏的属性。**@vararray*/protected$hidden=['password','remember_token',];/***获取将存储在JWT主题声明中的标识符。**@returnmixed*/publicfunctiongetJWTIdentifier(){return$this->getKey();}}/***返回一个键值数组,包含要添加到JWT的任何自定义声明。**@return数组*/publicfunctiongetJWTCustomClaims(){return[];}}注册在其之前构建的App/Http/Controller/Api/Auth/RegisterController.php添加如下内容:useApp\Http\Controllers\Controller;useApp\User;useDingo\Api\Exception\StoreResourceFailedException;useDingo\Api\Routing\Helpers;使用Illuminate\Foundation\Auth\RegistersUsers;使用Illuminate\Http\Request;使用Illuminate\Support\Facades\Validator;使用Tymon\JWTAuth\Facades\JWTAuth;类RegisterControllerextendsController{使用RegistersUsers;使用助手;公共函数寄存器(请求$request){$validator=$this->validator($request->all());if($validator->fails()){thrownewStoreResourceFailedException("验证错误",$validator->errors());$user=$this->create($request->all());如果($user->save()){$token=JWTAuth::fromUser($user);返回$this->response->array(["token"=>$token,"message"=>"Usercreated","status_code"=>201]);}else{return$this->response->error("找不到用户...",404);}}protectedfunctionvalidator(array$data){returnValidator::make($data,['name'=>'required|unique:users','email'=>'required|email|max:255|unique:users','password'=>'required|min:6',]);}protectedfunctioncreate(array$data){returnUser::create(['name'=>$data['name'],'email'=>$data['email'],'password'=>bcrypt($数据['密码']),]);}}打开Postman进行测试地址:http://127.0.0.1/myApiProject...登录在之前构建的App/Http/Controller/Api/Auth/LoginController.phpuseApp\User;useDingo\Api\Routing\Helpers;使用Illuminate\Foundation\Auth\AuthenticatesUsers;使用Illuminate\Http\Request;使用App\Http\Controllers\Controller;使用Illuminate\Support\Facades\Hash;使用Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;使用Tymon\JWTAuth\Facades\JWTAuth;classLoginControllerextendsController{使用AuthenticatesUsers;使用助手;publicfunctionlogin(Request$request){$user=User::where('email',$request->email)->orWhere('name',$request->email)->first();if($user&&Hash::check($request->get('password'),$user->pas剑)){$token=JWTAuth::fromUser($user);返回$this->sendLoginResponse($request,$token);}返回$this->sendFailedLoginResponse($request);}publicfunctionsendLoginResponse(Request$request,$token){$this->clearLoginAttempts($request);返回$this->authenticated($token);}publicfunctionauthenticated($token){return$this->response->array(['token'=>$token,'status_code'=>200,'message'=>'UserAuthenticated']);}publicfunctionsendFailedLoginResponse(){thrownewUnauthorizedHttpException("BadCredentials");}publicfunctionlogout(){$this->guard()->logout();}}打开Postman进行测试地址:http://127.0.0.1/myApiProject...可以看到我们拿到了拉取用户信息的token,在routers/api.php->group(['middleware'=>'api.auth'],function($api){$api->get('user','App\Http\Controllers\Api\UsersController@index');});终端运行:phpartisanmake:controllerApp\\Http\\Controllers\\Api\\UsersController在UsersController.php中添加命名空间App\Http\Controllers\Api;useDingo\Api\Routing\Helpers;useIlluminate\Routing\Controller;classUsersControllerextendsController{使用Helpers;公共函数__construct(){$this->middleware('api.auth');}publicfunctionindex(){//returnUser::all();$user=$this->auth->user();返回$用户;}}打开Postman进行测试地址:http://127.0.0.1/myApiProject...注意因为我们设置了拉取数据需要token,所以我们在请求头中添加:Authorization:Bearer+tokenBearer是一个源码中提到的token_type,应该是一个标准的总结,这里只提到了注册和登录,没有管理token,以后有时间再写。我已经花了很多工作时间。.