我是靠谱客的博主 大意绿草,这篇文章主要介绍Laravel5.4简单实现app接口Api Token认证方法,现在分享给大家,希望可以做个参考。

我是小白,今天写这篇文章主要是给新手学习看的,大佬就不用看了,有很多不足望大家指出,共同进步。

在开发中许多 API 通常在返回响应之前都需要某种形式的认证,有些时候,一个认证的请求和一个未认证的请求,响应可能不同。

在web项目中,实现认证比较轻松,那么前后端分离的项目中,我们要怎么实现认证,今天这篇文章就以 API token 认证机制,使用Token可以解决laravel API的无状态认证。

一、给用户表users增加api_token字段

复制代码
1
php artisan make:migration add_api_token_to_users

首先,给用户表中增加 api_token字段,在生成的迁移文件中添加字段:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?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) { $table->dropColumn(['api_token']); //新增加的 }); } }

二、然后使用下面的命令将字段添加到表中:

复制代码
1
php artisan migrate

三、用户注册:

在注册的控制器文件的创建用户中添加 api_token 字段:

我这里的控制器是AppHttpControllersApiRegisterController.php

复制代码
1
2
3
4
5
6
7
8
9
10
protected function register(Request $request) { $input = $request->all(); //获取传过来的传数 //在这里设置生成token后,与账号密码等信息一起存进User表 $user = User::create($data); //存进数据库 return $token; //这里面的逻辑自己写 我这里只是简单实现 }

最后,不要忘记在 AppUser.php用户模型表中的 $fillable 属性当中添加api_token字段:

复制代码
1
2
3
4
5
6
7
8
/** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password','confirmation_token','api_token' ];

四、修改api driver:

接下来要在configauth.php 修改如下内容:

复制代码
1
2
3
4
5
6
7
8
9
10
11
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', //把driver设置为token 'provider' => 'users', ], ],

五、如何使用:

接下来,我们要添加路由,在routesapi.php文件修改:

复制代码
1
2
3
Route::group(['middleware' => 'token'], function(){ Route::post('register', 'APIUserController@register'); });

怎么访问?我们这里用postman来测试:


到些就大功告成了! 注意,这个只是基础认证,现在开发还是用别人已经开发好的插件好,比如oAuth2,basic,jwt,Passport等等。

哦对了,如果想看token的认证原理,我们可以看他的底层源码

vendorlaravelframeworksrcIlluminateAuthTokenGuard.php:

这个我也看不明白,哈!再见!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持靠谱客。

最后

以上就是大意绿草最近收集整理的关于Laravel5.4简单实现app接口Api Token认证方法的全部内容,更多相关Laravel5.4简单实现app接口Api内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(149)

评论列表共有 0 条评论

立即
投稿
返回
顶部