Java教程

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

本文主要是介绍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

<?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)

 

 

把生成的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

 

这篇关于Laravel 5.8 做个知乎 13 —— Api token用户认证的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!