Authentication on Laravel API routes

Asked

Viewed 330 times

0

I’m conducting some tests in the construction of a API with Laravel. At the moment all URLS of API are with access without authentication. I am trying to allow after user authentication.

In Routes/api.php I am setting:

<?php

use Illuminate\Http\Request;

Auth::routes();
Route::get('/member/{id}', 'PessoaController@edit')->middleware('auth:api');

And in my controller it’s set that way:

<?php

  namespace App\Http\Controllers;

  use App\Pessoa;
  use JsValidator;
  use Illuminate\Support\Facades\Validator;
  use Illuminate\Http\Request;
  use Illuminate\Support\Facades\DB;
  use App\Http\Requests\PessoaRequest;

  date_default_timezone_set('America/Sao_Paulo');

   class PessoaController extends Controller
 {

public function __construct(Pessoa $pessoa)
{
    $this->Pessoa = $pessoa;
    $this->middleware('auth.api')->except(['index', 'show']);
    $this->middleware('auth.api:optional')->only(['index', 'show']);
}
}

1 answer

1

Why set another Api within Routes? See how I do.

Inside the Routes.php

Route::resource('pessoas', 'PessoasController');

And inside the controller

public function __construct()
{
    $this->middleware('auth', ['only' => ['index']]); // exigir permissão para acessar
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.