解决上一节当中如果api路由改成:
1 Route::middleware('auth:api')->post('/questions/follow', 'QuestionController@followThroughApi');之后 axios ajax post请求报 401 unauthorized
异常的问题。
原理
:
教程
:
Building SPAs with Laravel 5 and Vue.js 2 - Finishing Up
修改指导:简单来说,auth要求的token我们没有提供:
通过api访问走的是token认证,这里没有提供token所以就认证失败返回401了
这个tokendriver对应的其实就是:
这个TokenGuard.php文件,这里面需要一个api_token。需要在request里提供api_token参数,为了区别是哪个用户,需要在user表添加api_token字段。认证过程调用的是TokenGuard.php中的getTokenForRequest方法:
这个bearerToken实际找header中是否存在Authorization
我们需要来提供这个token:
原理参考:
BearerToken:
本质上给用户表添加api_token,后台根据这个字段判断是否是有效的用户,无效返回401,有效返回查询结果。
优点是容易理解,缺点太简单,安全也不够。
为了安全,可以实现下面的功能:每次登录成功后刷新api_token为新值
其实 Laravel 官方提供了一个 Laravel Passport 的包。Laravel Passport is an OAuth2 server and API authentication package 。搞一搞laravel里api路由的 auth:api 和 api_token
JWT(Json Web Token):
【但是并不建议真实生产环境下用下面的方法,建议用官方的passport或者jwt
】
步骤:
执行命令:
1 php artisan make:migration add_api_token_to_users_table --table=users编辑****_add_api_token_to_users_table.php文件:
_add_api_token_to_users_table.php1 <?php 2 3 use Illuminate\Database\Migrations\Migration; 4 use Illuminate\Database\Schema\Blueprint; 5 use Illuminate\Support\Facades\Schema; 6 7 class AddApiTokenToUsersTable extends Migration 8 { 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::table('users', function (Blueprint $table) { 17 // 18 $table->string('api_token', 64)->unique()->comment("api验证token"); 19 }); 20 } 21 22 /** 23 * Reverse the migrations. 24 * 25 * @return void 26 */ 27 public function down() 28 { 29 Schema::table('users', function (Blueprint $table) { 30 // 31 $table->dropColumn('api_token'); 32 }); 33 } 34 } 35 36