Laravel 5.4 API token authentication

Time:2021-9-22

In this article, we will use the API token authentication mechanism separated from the front end and the back end. Using token can solve the stateless authentication mechanism of API.

problem

Middleware is used in api.php interfacemiddleware('auth:api')Problems with permission verification:

Laravel 5.4 API token authentication

//Request 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');

According to the error prompt, you need to verify the permissions of the API interface. See the following for the specific steps:

1、 Add API to user table users_ Token field

php artisan make:migration add_api_token_to_users --table=users

Created Migration: 2017_03_21_235545_add_api_token_to_users

Add fields to the generated migration file:

<?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']);
        });
    }
}

Then use the following command to add fields to the table:

php artisan migrate

Laravel 5.4 API token authentication

2、 When a user registers, an API needs to be generated_ token

stayApp\Http\Controllers\Auth\RegisterController.phpAdded to the user who created the fileapi_tokenField;

/**
     * 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 authentication 
        ]);

        $this->sendVerifyEmailTo($user);

        return $user;
    }

Finally, don’t forget toApp\User.phpIn the user model table$fillablePropertyapi_tokenField:

  /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','avatar','confirmation_token','phone','api_token'
    ];

3、 Use

For the principle of token authentication, we can see the underlying methods under this directory:
vendor\laravel\framework\src\Illuminate\Auth\TokenGuard.php

1. Rewriteresource\assets\js\bootstrap.jsCertification method:

/*
  //API token certification - [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. Add API in app.blade.php_ Token judgment

<!-- Scripts -->
    <script>
        window.Laravel = {!! json_encode([
            'csrfToken' => csrf_token(),
        ]) !!};

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

Related articles:
Laravel’s API authentication system passport
Two setting methods of x-csrf-token in laravel 5.4 Vue framework
Ajax request for [daily pit filling] API interface of laravel