Laravel安装Passport验证以及报错解决办法

一,安装
使用Composer安装Passport

	composer require laravel/passport

Passport的服务提供者注册到配置文件config/app.phpproviders中:

	Laravel\Passport\PassportServiceProvider::class,

Passport服务提供器使用框架注册自己的数据库迁移目录,因此在注册提供器后,就应该运行Passport的迁移命令来自动创建存储客户端和令牌的数据表

	php artisan migrate

执行php artisan migrate出现报错一

	$ php artisan migrate
	
	   Illuminate\Database\QueryException  : could not find driver (SQL: select * fr
	om information_schema.tables where table_schema = dev_oms and table_name = migra
	tions)
	
	  at D:\WWW\dev_oms\vendor\laravel\framework\src\Illuminate\Database\Connection.
	php:664
	    660|         // If an exception occurs when attempting to run a query, we'll
	 format the error
	    661|         // message to include the bindings with SQL, which will make th
	is exception a
	    662|         // lot more helpful to the developer instead of just the databa
	se's errors.
	    663|         catch (Exception $e) {
	  > 664|             throw new QueryException(
	    665|                 $query, $this->prepareBindings($bindings), $e
	    666|             );
	    667|         }
	    668|
	
	  Exception trace:
	
	  1   PDOException::("could not find driver")
	      D:\WWW\dev_oms\vendor\laravel\framework\src\Illuminate\Database\Connectors
	\Connector.php:68
	
	  2   PDO::__construct("mysql:host=127.0.0.1;port=3306;dbname=api6", "root",
	"root", [])
	      D:\WWW\dev_oms\vendor\laravel\framework\src\Illuminate\Database\Connectors
	\Connector.php:68
	
	  Please use the argument -v to see more details.

解决办法:开启php.ini 扩展"php_pdo_mysql.dll"
在这里插入图片描述
报错二:

	$ php artisan migrate
	Migration table created successfully.
	
	   Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access
	 violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: a
	lter table `users` add unique `users_email_unique`(`email`))
	
	  at D:\WWW\dev_oms\vendor\laravel\framework\src\Illuminate\Database\Connection.
	php:664
	    660|         // If an exception occurs when attempting to run a query, we'll
	 format the error
	    661|         // message to include the bindings with SQL, which will make th
	is exception a
	    662|         // lot more helpful to the developer instead of just the databa
	se's errors.
	    663|         catch (Exception $e) {
	  > 664|             throw new QueryException(
	    665|                 $query, $this->prepareBindings($bindings), $e
	    666|             );
	    667|         }
	    668|
	
	  Exception trace:
	
	  1   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Sp
	ecified key was too long; max key length is 767 bytes")
	      D:\WWW\dev_oms\vendor\laravel\framework\src\Illuminate\Database\Connection
	.php:458
	
	  2   PDOStatement::execute()
	      D:\WWW\dev_oms\vendor\laravel\framework\src\Illuminate\Database\Connection
	.php:458
	
	  Please use the argument -v to see more details. 

将数据库编码改为utf8mb4或utf8–utf-8 unicode
在这里插入图片描述
报错三:

	$ php artisan migrate
	Migration table created successfully.
	
	   Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access
	 violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: a
	lter table `users` add unique `users_email_unique`(`email`))
	
	  at D:\WWW\dev_oms\vendor\laravel\framework\src\Illuminate\Database\Connection.
	php:664
	    660|         // If an exception occurs when attempting to run a query, we'll
	 format the error
	    661|         // message to include the bindings with SQL, which will make th
	is exception a
	    662|         // lot more helpful to the developer instead of just the databa
	se's errors.
	    663|         catch (Exception $e) {
	  > 664|             throw new QueryException(
	    665|                 $query, $this->prepareBindings($bindings), $e
	    666|             );
	    667|         }
	    668|
	
	  Exception trace:
	
	  1   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Sp
	ecified key was too long; max key length is 767 bytes")
	      D:\WWW\dev_oms\vendor\laravel\framework\src\Illuminate\Database\Connection
	.php:458
	
	  2   PDOStatement::execute()
	      D:\WWW\dev_oms\vendor\laravel\framework\src\Illuminate\Database\Connection
	.php:458
	
	  Please use the argument -v to see more details.

在app\Providers\AppServiceProvider.php中添加两行代码

	use Illuminate\Support\Facades\Schema;
	
    public function boot()
    {
        //新增
        Schema::defaultStringLength(191);
    }

在这里插入图片描述
二,配置
1,应用配置

将Laravel\Passport\HasApiTokens Trait添加到App\User模型中,这个Trait会给你的模型提供一些辅助函数,用于检查已认证用户的令牌和使用范围:

在这里插入图片描述
然后在AuthServiceProvider的boot方法中调用Passport::routes函数。这个函数会注册发出访问令牌并撤销访问令牌、客户端和个人访问令牌所必需的路由:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200613152750898.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDI0MzExMQ==,size_16,color_FFFFFF,t_70在这里插入图片描述
最后,将配置文件config/auth.php中授权看守器guards的api的driver选项改为passport。此调整会让你的应用程序在在验证传入的API的请求时使用Passport的TokenGuard来处理:
在这里插入图片描述
2、部署 Passport
第一次将Passport部署到生产服务器时,需要运行passport:keys命令。该命令生成Passport所需要的用来产生访问令牌的加密密钥。生成的这些公钥和私钥保存在storage/oauth-private.key:

	php artisan passport:keys

3、创建用户
使用seed来创建用户

	php artisan make:seeder UsersTableSeeder

进入database\seeds\UsersTableSeeder.php的run中写入代码:

	DB::table('users')->insert([
	    'name'=>'users',
	    'email'=>'110@qq.com',
	    'password'=>bcrypt('账号密码')
	]);

运行一下代码填充数据

	php artisan db:seed --class=UsersTableSeeder

三:登录注册代码编写
创建控制器

	php artisan make:controller API/UserController

API文件编写

//登录
	Route::post('login', 'API\UserController@login');
	//注册
	Route::post('register', 'API\UserController@register');
	
	//授权的接口
	Route::group(['middleware' => 'auth:api'], function () {
	//获取用户信息
	    Route::get('user', 'API\UserController@user');
	});

在这里插入图片描述
控制器代码展示

	    public $SuccessCode = 200;
	
	//    登录
	    public function login()
	    {
	        if (Auth::attempt(['name' => request('name'), 'password' => request('password')])) {
	            $user = Auth::user();
	            $success['token'] = $user->createToken('MyApp')->accessToken;
	            return Response()->json(['success' => $success], $this->SuccessCode);
	        } else {
	            return Response()->json(['error' => '授权失败'], 401);
	        }
	    }
	
	
	    /**
	     * register function
	     *
	     * 注册
	     */
	    public function register(Request $request)
	    {
	        $validator = Validator::make($request->all(), [
	            'name' => 'required',
	            'email' => 'required|email',
	            'password' => 'required',
	            'passwords' => 'required|same:password',
	        ]);
	
	        if ($validator->fails()) {
	            return Response()->json(['error' => $validator->errors()], 401);
	        }
	
	        // 这里根据自己表结构修改
	        $input = $request->all();
	        $input['password'] = bcrypt($input['password']);
	        $input['avatar'] = '/images/avatars/default.jpg';
	        $input['emailverfiy_token'] = '';
	        $input['state'] = 1;
	        $user = User::create($input);
	        $success['token'] = $user->createToken('MyApp')->accessToken;
	        $success['name'] = $user->name;
	        return Response()->json(['success' => $success], $this->SuccessCode);
	    }
	    
	//获取用户信息
	    public function users(Request $request){
	
	        $user = Auth::user();
	        return Response()->json(['success'=>$user],$this->SuccessCode);
	    }

postman测试登录
在这里插入图片描述

注册
在这里插入图片描述

获取用户信息

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傅先生的傅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值