• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

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

开发技术 开发技术 3小时前 1次浏览

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

databasemigrations2021_07_20_210539_add_api_token_to_users.php

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

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

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 appHttpControllersAuthRegisterController.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 appUser.php

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

2.2 接口代码

2.2.1 resourcesjsbootstrap.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用户认证
喜欢 (0)