我是小白,今天写这篇文章主要是给新手学习看的,大佬就不用看了,有很多不足望大家指出,共同进步。
在开发中许多 API 通常在返回响应之前都需要某种形式的认证,有些时候,一个认证的请求和一个未认证的请求,响应可能不同。
在web项目中,实现认证比较轻松,那么前后端分离的项目中,我们要怎么实现认证,今天这篇文章就以 API token 认证机制,使用Token可以解决laravel API的无状态认证。
一、给用户表users增加api_token字段
php artisan make:migration add_api_token_to_users
首先,给用户表中增加 api_token字段,
在生成的迁移文件中添加字段:
<?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']); //新增加的
});
}
}