laravel 5.4 api.php,Laravel5.4 Api Token认证

本片文章,我们将使用前后端分离的 API token 认证机制,使用Token可以解决API的无状态认证机制。

问题

api.php中接口使用中间件 middleware('auth:api')权限验证会出现问题:

0818b9ca8b590ca3270a3433284dd417.png

// 请求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

在生成的迁移文件中添加字段:

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

0818b9ca8b590ca3270a3433284dd417.png

二、用户注册时,需生成一个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 判断

window.Laravel = {!! json_encode([

'csrfToken' => csrf_token(),

]) !!};

Laravel.apiToken = "{{ Auth::check() ? 'Bearer '.Auth::user()->api_token : 'Bearer ' }}";

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值