'Getting an Unauthenticated message while trying to access my register route on my API Laravel
I'm trying to access my register function with a post route, but when doing so and testing it on Postman, I get the following error:
"message": "Unauthenticated."
I know some people faced the same issue and posted a question here, but none of the answers solved my problem, for example, if I add '->name('login')' after my route, I'm getting a new error :
The GET method is not supported for this route. Supported methods: POST. whereas I'm accessing my route with a POST method.
Any idea why I'm getting that ?
api.php:
<?php
use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/register', [AuthController::class, 'register']);
Route::group(['middleware' => ['auth:sanctum']], function() {
Route::resources([
'constituencies' => \App\Http\Controllers\ConstituencyController::class,
'candidates' => \App\Http\Controllers\CandidateController::class,
'participations' => \App\Http\Controllers\ParticipationController::class,
'towns' => \App\Http\Controllers\TownController::class,
'users' => \App\Http\Controllers\UserController::class,
'vote_centers' => \App\Http\Controllers\VoteCenterController::class,
]);
});
Route::post('/tokens/create', function (Request $request) {
$token = $request->user()->createToken($request->token_name);
return ['token' => $token->plainTextToken];
});
AuthController.php :
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function register(Request $request) {
$fields = $request->validate([
'name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed'
]);
$user = User::create([
'name' => $fields['name'],
'email' => $fields['email'],
'password' => bcrypt($fields['password'])
]);
$token = $user->createToken('myapptokken')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response,201);
}
}
web.php:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
RouteServiceProvider.php:
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}
I'm also using Laravel Sanctum, does it change anything?
Thanks !
UPDATE: Route List:
GET|HEAD / ..................................................................................................................................................................................................................
POST _ignition/execute-solution ........................................................................................................... ignition.executeSolution › Spatie\LaravelIgnition › ExecuteSolutionController
GET|HEAD _ignition/health-check ....................................................................................................................... ignition.healthCheck › Spatie\LaravelIgnition › HealthCheckController
POST _ignition/update-config .................................................................................................................... ignition.updateConfig › Spatie\LaravelIgnition › UpdateConfigController
GET|HEAD api/candidates ........................................................................................................................................................ candidates.index › CandidateController@index
POST api/candidates ........................................................................................................................................................ candidates.store › CandidateController@store
GET|HEAD api/candidates/create ............................................................................................................................................... candidates.create › CandidateController@create
GET|HEAD api/candidates/{candidate} .............................................................................................................................................. candidates.show › CandidateController@show
PUT|PATCH api/candidates/{candidate} .......................................................................................................................................... candidates.update › CandidateController@update
DELETE api/candidates/{candidate} ........................................................................................................................................ candidates.destroy › CandidateController@destroy
GET|HEAD api/candidates/{candidate}/edit ......................................................................................................................................... candidates.edit › CandidateController@edit
GET|HEAD api/constituencies ............................................................................................................................................. constituencies.index › ConstituencyController@index
POST api/constituencies ............................................................................................................................................. constituencies.store › ConstituencyController@store
GET|HEAD api/constituencies/create .................................................................................................................................... constituencies.create › ConstituencyController@create
GET|HEAD api/constituencies/{constituency} ................................................................................................................................ constituencies.show › ConstituencyController@show
PUT|PATCH api/constituencies/{constituency} ............................................................................................................................ constituencies.update › ConstituencyController@update
DELETE api/constituencies/{constituency} .......................................................................................................................... constituencies.destroy › ConstituencyController@destroy
GET|HEAD api/constituencies/{constituency}/edit ........................................................................................................................... constituencies.edit › ConstituencyController@edit
POST api/login ..................................................................................................................................................................................... AuthController@login
POST api/logout ................................................................................................................................................................................... AuthController@logout
GET|HEAD api/participations ............................................................................................................................................ participations.index › ParticipationController@index
POST api/participations ............................................................................................................................................ participations.store › ParticipationController@store
GET|HEAD api/participations/create ................................................................................................................................... participations.create › ParticipationController@create
GET|HEAD api/participations/{participation} .............................................................................................................................. participations.show › ParticipationController@show
PUT|PATCH api/participations/{participation} .......................................................................................................................... participations.update › ParticipationController@update
DELETE api/participations/{participation} ........................................................................................................................ participations.destroy › ParticipationController@destroy
GET|HEAD api/participations/{participation}/edit ......................................................................................................................... participations.edit › ParticipationController@edit
POST api/register ............................................................................................................................................................................... AuthController@register
POST api/tokens/create ..................................................................................................................................................................................................
GET|HEAD api/towns ....................................................................................................................................................................... towns.index › TownController@index
POST api/towns ....................................................................................................................................................................... towns.store › TownController@store
GET|HEAD api/towns/create .............................................................................................................................................................. towns.create › TownController@create
GET|HEAD api/towns/{town} .................................................................................................................................................................. towns.show › TownController@show
PUT|PATCH api/towns/{town} .............................................................................................................................................................. towns.update › TownController@update
DELETE api/towns/{town} ............................................................................................................................................................ towns.destroy › TownController@destroy
GET|HEAD api/towns/{town}/edit ............................................................................................................................................................. towns.edit › TownController@edit
GET|HEAD api/user ...........................................................................................................................................................................................................
GET|HEAD api/users ....................................................................................................................................................................... users.index › UserController@index
POST api/users ....................................................................................................................................................................... users.store › UserController@store
GET|HEAD api/users/create .............................................................................................................................................................. users.create › UserController@create
GET|HEAD api/users/{user} .................................................................................................................................................................. users.show › UserController@show
PUT|PATCH api/users/{user} .............................................................................................................................................................. users.update › UserController@update
DELETE api/users/{user} ............................................................................................................................................................ users.destroy › UserController@destroy
GET|HEAD api/users/{user}/edit ............................................................................................................................................................. users.edit › UserController@edit
GET|HEAD api/vote_centers ................................................................................................................................................... vote_centers.index › VoteCenterController@index
POST api/vote_centers ................................................................................................................................................... vote_centers.store › VoteCenterController@store
GET|HEAD api/vote_centers/create .......................................................................................................................................... vote_centers.create › VoteCenterController@create
GET|HEAD api/vote_centers/{vote_center} ....................................................................................................................................... vote_centers.show › VoteCenterController@show
PUT|PATCH api/vote_centers/{vote_center} ................................................................................................................................... vote_centers.update › VoteCenterController@update
DELETE api/vote_centers/{vote_center} ................................................................................................................................. vote_centers.destroy › VoteCenterController@destroy
GET|HEAD api/vote_centers/{vote_center}/edit .................................................................................................................................. vote_centers.edit › VoteCenterController@edit
GET|HEAD sanctum/csrf-cookie .................................................................................................................................................... Laravel\Sanctum › CsrfCookieController@show
Kernel.php:
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,
'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
