Andrey Fugas
Andrey Fugas

Reputation: 61

How change UnauthorizedHttpException errorHandler auth.basic in Laravel

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'));
}

Upvotes: 0

Views: 3106

Answers (1)

Mateus Junges
Mateus Junges

Reputation: 2602

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.

Upvotes: 0

Related Questions