Laravel5.4 Api Token认证
本片文章,我们将使用前后端分离的 API token 认证机制,使用Token可以解决API的无状态认证机制。
问题
api.php中接口使用中间件 middleware('auth:api')
权限验证会出现问题:
// 请求Api url Route::post('question/follower', function(Request $request){ $followed = \App\Models\Follow::where('question_id', $request->get('question')) ->where('user_id', $request->get('user')) ->count(); if($followed) { return response()->json(['followed' => true]); } return response()->json(['followed' => false]); })->middleware('auth:api');
根据错误提示,需要给api接口进行权限的验证,具体步骤可看下边:
一、给用户表users增加api_token字段
php artisan make:migration add_api_token_to_users --table=users
Created Migration: 2017_03_21_235545_add_api_token_to_users
在生成的迁移文件中添加字段:
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddApiTokenToUsers extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('api_token', 64)->unique(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn(['api_token']); }); } }
然后使用下面的命令将字段添加到表中:
php artisan migrate
二、用户注册时,需生成一个api_token
在 App\Http\Controllers\Auth\RegisterController.php
文件的创建用户中添加 api_token
字段;
/** * Create a new user instance after a valid registration. * * @param array $data * @return User */ protected function create(array $data) { $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'avatar' => '/images/avatars/default.png', 'phone' => '', 'confirmation_token' => str_random(40), 'password' => bcrypt($data['password']), 'api_token' => str_random(60), // api_token认证 ]); $this->sendVerifyEmailTo($user); return $user; }
最后,不要忘记在 App\User.php
用户模型表中的 $fillable
属性当中添加api_token
字段:
/** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password','avatar','confirmation_token','phone','api_token' ];
三、使用
有关token认证的原理,我们可以看该目录下的底层方法:vendor\laravel\framework\src\Illuminate\Auth\TokenGuard.php
1.重写resource\assets\js\bootstrap.js
认证方法:
/* // API token 认证-【20170321】 window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': window.Laravel.csrfToken, 'X-Requested-With': 'XMLHttpRequest' }; */ window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': window.Laravel.csrfToken, 'Authorization': window.Laravel.apiToken };
2. app.blade.php中增加api_token 判断
<!-- Scripts --> <script> window.Laravel = {!! json_encode([ 'csrfToken' => csrf_token(), ]) !!}; Laravel.apiToken = "{{ Auth::check() ? 'Bearer '.Auth::user()->api_token : 'Bearer ' }}"; </script>
相关文章:
Laravel 的 API 认证系统 Passport
Laravel5.4 Vue 框架中 X-CSRF-TOKEN 的两种设置方法
【日常填坑】之ajax请求laravel的api接口
相关推荐
RocketJ 2020-06-09
qidiantianxia 2020-10-21
kiven 2020-09-11
wolfjin 2020-09-10
HMHYY 2020-06-28
苦咖啡flask 2020-06-18
playis 2020-06-16
xuanwenchao 2020-06-14
sqliang 2020-06-14
TesterJingel 2020-06-10
powderhose 2020-06-08
rongxionga 2020-06-08
Burgesszheng 2020-06-07
huangyx 2020-05-29
RuoShangM 2020-05-14
数据库之扑朔迷离 2020-05-06