laravel 配置 api token

简介

Laravel API 默认驱动为token,文档上没介绍如何使用,下面让我们来实现它。

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

配置字段

项目下执行命令php artisan make:migration update_users_table_for_api_token --table=users生成迁移文件.

修改迁移文件

/**
     * Run the migrations.
     *
     * @return void
     */
  public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            //字段名固定,长度建议32以上
            $table->string('api_token', 64)->unique();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('api_token');
        });
    }

项目下执行命令php artisan migrate执行迁移。数据表users会添加api_token字段

配置模型

添加api_tokenUser模型$fillable$hidden属性

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','api_token'
    ];

生成api_token

代码放在注册控制器app/Http/Controllers/Auth/RegisterController.php里面。

/**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'api_token' =>str_random(64)
        ]);
    }

用户注册成功后自动分配一个api_token

配置API路由

routes/api.php里面配置路由,使用token方式时一定要使用中间件auth:api
系统已经帮我们配置了一个Api路由,我们可以直接使用这个路由测试。

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

通过api_token获取用户

  • 通过GETPOST发送api_token字段数据获取用户。
  • 通过header头部发送Authorization获取用户。
//方式GuzzleHttp\Client
 //假如你的token为DntgHWoEanBSYeMv,为了显示效果截取了长度
 //GuzzleHttp\Client方式
    $guzzle = new GuzzleHttp\Client;
        $response = $guzzle->get('http://mysite/api/user', [
            'headers' => [
                'Authorization' => 'Bearer DntgHWoEanBSYeMv',
            ],
        ]);

        print_r( json_decode((string) $response->getBody(), true));
//假如你的token为DntgHWoEanBSYeMv,为了显示效果截取了长度
//jQuery方式
    $.ajaxSetup({
        headers:{
                Authorization:'Bearer DntgHWoEanBSYeMv'
        }
    });

    $.get('http://yoursite.com/api/user').
    then(function(data) {
       console.log(data);
    });

//axios方式
axios.defaults.headers.common['Authorization'] = 'Bearer DntgHWoEanBSYeMv';

axios.get('http://yoursite.com/api/user')
  .then(function(response) {
       console.log(response.data);
    });

注意这里有跨域问题,可以设置Access-Control-Allow系列header解决跨域问题,
也有现成的中间件barryvdh/laravel-cors可以使用。

[参考] https://segmentfault.com/a/1190000006215513

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lxfamn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值