Home > Software design >  how to return a custom error message when someone is trying to access a protected group of routes in
how to return a custom error message when someone is trying to access a protected group of routes in

Time:08-14

question: i have several routes in my API , grouped with middleware 'sanctum', like below:

Route::group(['middleware' => ['auth:sanctum']],function() {
    Route::put('/products/{id}',[ProductController::class,'update']);
    Route::post('/products',[ProductController::class,'store']);
    Route::delete('/products/{id}',[ProductController::class,'destroy']);
    Route::post('/authlogout',[AuthController::class,'authLogout']);
});

now i want to show a custom error message when someone is trying to access these routes without appropriate credentials, currently, when someone tries to access them, he/she would get something like below:

Symfony\Component\Routing\Exception\RouteNotFoundException: Route [login] not defined. in file /home/arash/LaravelTests/smart-finance/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php on line 444

but I just want a simple ['error' => 'authentication failed'] message, how can I do that? ( showing a simple response when someone tries to access any of these routes without the needed credentials?

CodePudding user response:

Pass header Accept as application/json.if you are not passing then you get mentioned error.For reference attached screenshot for better understanding.

After passing Accept header as application/json response

enter image description here

Accept

The Accept request HTTP header indicates which content types, expressed as MIME types, the client is able to understand. The server uses content negotiation to select one of the proposals and informs the client of the choice with the Content-Type response header. Browsers set required values for this header based on the context of the request. For example, a browser uses different values in a request when fetching a CSS stylesheet, image, video, or a script.

if you are looking for custom response then you can handle by overriding exceptions.

In app/Exceptions/Handler.php add the following method

/**
 * Convert an authentication exception into a response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Symfony\Component\HttpFoundation\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
        ? response()->json(['error' =>"authentication failed"], 401)
        : redirect()->guest($exception->redirectTo() ?? route('login'));
}
  • Related