发布于 2017-03-24 10:44:25 | 708 次阅读 | 评论: 0 | 来源: PHPERZ

这里有新鲜出炉的Laravel 5教程,程序狗速度看过来!

Laravel PHP Web开发框架

Laravel是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。


本片文章,我们将使用前后端分离的 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接口



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务