Laravel5.5 api token 用法
2018年8月10日1.首先要在用户表中添加 api_token
字段
打开 database/migrations/2014_10_12_000000_create_users_table.php
添加 api_token 字段
1 2 3 4 5 6 7 8 9 10 |
Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); //添加 api_token 字段 $table->string('api_token', 64)->unique(); $table->rememberToken(); $table->timestamps(); }); |
然后你可以重置并重新运行migration
1 2 |
php artisan migrate:reset php artisan migrate |
1.1用户注册的时候自动生成token
编辑\app\Http\Controllers\Auth\RegisterController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/** * 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) ]); } |
2.设置路由
这里可以添加 throttle 这个中间件他可以限制请求访问的次数默认一分钟60次.
1 2 3 4 5 6 |
Route::prefix('v1')->middleware('auth:api')->group(function() { // 取单条数据 Route::get('notes/{id}',function($id){ return Note::select('title', 'content')->find($id); }); }); |
3.修改用户模型
添加 api_token
字段
1 2 3 4 5 6 7 |
protected $fillable = [ //可以creted 'name', 'email', 'password','api_token' ]; protected $hidden = [ //隐藏 'password', 'remember_token','api_token' ]; |
4.返回用户信息
1 |
Auth::guard('api')->user(); |
5.如何请求
加上参数token就可以了
1 |
http://xxx.com/notes?api_token=xxxxxxxxxx |