0
votes

I'm trying to make api with basic auth in Laravel 5.5.48
When auth is success ('username' and 'password') response is correct, but if auth is unsuccess(wrong 'username' and 'password' data) displays error

What I haven't tried, but I couldn't change Exception displays on my response (response()->json(['status'=>'auth failed']))

routes/api.php

Route::post('/index', 'Api\MyController@index')->middleware('auth.basic');

app/Http/Controllers/Api/MyController@index

public function index(Request $request)
{
    return response()->json(array('status' => 'success'));
}
2

2 Answers

0
votes

Beware that the error you get is by design to help you debug in localhost, if you changed your APP_ENV to 'production' and APP_DEBUG=false  it won't show the entire error stack

However, to catch the error and handle it manually, return the custom response in App\Exceptions\Handler

public function render($request, Exception $exception)
{
    if ($exception instanceof Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException) {
        return response()->json(['status'=>'auth failed'], 401);
    }
    return parent::render($request, $exception);
}
0
votes

You can use the Exception handler:

Within app/Exceptions/Handler.php:

public function render($request, Exception $exception)
{
    if ($exception instanceof UnauthorizedException) {
        return response()->json(['status'=>'auth failed'], Response::HTTP_UNAUTHORIZED);
    }

    return parent::render($request, $exception);
}

Don't forget to use UnauthorizedException and Response:

use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
use Symfony\Component\HttpFoundation\Response

Check here for more details about the Laravel Exception Handler.

Hope it helps.