How to use web and api guards at the same time in

2020-08-03 06:54发布

问题:

I have build application with two parts: RESTful part for mobiles and web.

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?

回答1:

Protect whatever routes are for your api with auth:api middleware

Route::group(['middleware' => ['auth:api']], function(){
    //protected routes for API
});

We must make sure that your users table has an api_token column:

php artisan make:migration alter_users_table_add_api_token_column

Then inside of the up function:

Schema::table('users', function($table){
    $table->string('api_token', 60)->unique(); //this must be 60 characters
});

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
    ]);
}

Now request to the auth:api protected routes will need to contain an api_token in their payload.