Laravel 5.8 做个知乎 13 —— Api token用户认证

0 设置

config/auth.php

'api' => [
    'driver' => 'token',
    'provider' => 'users',
    'hash' => true,
],

 

1 添加users表字段api_token

php artisn make:migration add_api_token_to_users --table=users

\database\migrations\2021_07_20_210539_add_api_token_to_users.php

Laravel 5.8 做个知乎 13 —— 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) {
            //
            $this->dropColum(['api_token']);
        });
    }
}
View Code
php artisan migrate

 

php artisan tinker
str_random(60)

 

Laravel 5.8 做个知乎 13 —— Api token用户认证

 

把生成的token添加到字段里

2 修改代码

2.1 注册相关代码

2.1.1 \app\Http\Controllers\Auth\RegisterController.php

    protected function create(array $data)
    {
        $user = User::create([
          'name' => $data['name'],
          'email' => $data['email'],
          'avatar' => '/image/avatars/default.jpg',
            //这里其实不需要再设置activation_token的值,也不需要再在验证后设置activated=1 采用Laravel提供的新功能验证用户邮箱即可 默认带一个email_verified_at字段,且更加完善具有过期时间戳和签名
          'activation_token' => str_random(40),//通过composer require laravel/helpers安装扩展包
          'password' => Hash::make($data['password']),
           //添加token
           'api_token'=>str_random(60)
        ]);
        $this->sendVerifyEmailTo($user);
        return $user;
    }

 

2.1.2 \app\User.php

    protected $fillable = [
        'name', 'email', 'password', 'avatar','activation_token','api_token'
    ];

2.2 接口代码

2.2.1 \resources\js\bootstrap.js

let api_token = document.head.querySelector('meta[name="api-token"]');
if (api_token) {
    window.axios.defaults.headers.common['Authorization'] = api_token.content;
} else {
    console.error('Authorization token not found');
}

2.2.2

 

上一篇:python 使用SMTP发送邮件


下一篇:Python 发送邮件