0

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

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.