如何在Laravel中同时使用Web和API防护? [英] How to use web and api guards at the same time in Laravel?
问题描述
我构建的应用程序包含两个部分:用于手机和Web的RESTful部分.
I have build application with two parts: RESTful part for mobiles and web.
如何同时使用Web/API保护工具?我可以使用stadart网络表单注册用户,并接受Restful之类的请求吗?
How can I use web/api guards at the same time? That I can register users with stadart web form, and accept request like as Restful?
推荐答案
使用auth:api
中间件
Route::group(['middleware' => ['auth:api']], function(){
//protected routes for API
});
我们必须确保您的users
表具有api_token
列:
We must make sure that your users
table has an api_token
column:
php artisan make:migration alter_users_table_add_api_token_column
然后在up
函数内部:
Schema::table('users', function($table){
$table->string('api_token', 60)->unique(); //this must be 60 characters
});
最后在您的App\Http\Controllers\Auth\RegisterController
中,修改创建文件以添加api_token
Finally in your App\Http\Controllers\Auth\RegisterController
, modify the create file to add your api_token
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'api_token' => str_random(60) //add this
]);
}
现在对受auth:api
保护的路由的请求将需要在其有效负载中包含api_token
.
Now request to the auth:api
protected routes will need to contain an api_token
in their payload.
这篇关于如何在Laravel中同时使用Web和API防护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!