0

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?

Babaev
  • 253
  • 1
  • 4
  • 11

1 Answers1

4

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.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • I dont have `AuthController` in Laravel 5.3 – Babaev Sep 05 '16 at 19:03
  • In your case how can I register user using `api_token`? – Babaev Sep 05 '16 at 19:04
  • @Babaev I've modified my answer. You'll need to make these modiications in the `App\Http\Controllers\Auth\RegisterController` under the `create()` function. – Ohgodwhy Sep 05 '16 at 19:27
  • Okay, but how to register new user using RESTful interface? – Babaev Sep 05 '16 at 19:50
  • @Babaev All users are given an api_token on creation. How they get created is up to you. – Ohgodwhy Sep 05 '16 at 19:53
  • I dont understand you, my service is used by mobile clients, they should have registration from mobile device, sending RESTful reuest with user data – Babaev Sep 05 '16 at 19:58
  • Ok. Send the request over https with a JSON payload to register. When they're created, they'll still get an `api_token` column. When sending further requests when they're logged in, make sure that the `api_token` from the `auth()->guard('api')->user()->api_token` is being used in the payload as the `api_token` parameter. Any routes you want to be resourceful, place them under the `Route::group` i showed you above, and simply do `Route::resource('model', 'controller');` – Ohgodwhy Sep 05 '16 at 20:11
  • Could you share an example please, it is very important – Babaev Sep 05 '16 at 22:27