php laravel token,Laravel API Token 体验

适用laravel版本5.3+

简介

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_token到User模型$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

2dcbf58d33dbe2f5f7378d6f8dd06a30.png

配置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获取用户

通过GET,POST发送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可以使用。

本作品采用《CC 协议》,转载必须注明作者和本文链接

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值