Laravel 5 - Change JSON response to request with wrong api token.


If you used laravel 5 passport then i am sure you require to use "auth:api" middleware, But you can see when you pass wrong api token then you just get "unauthenticated" json response with error key. If you want to change message or json formate then you can do it.

You have to on on default Exceptions handler file and you can change there. So just open your Handler.php file and change json response.

app/Exceptios/Handler.php

<?php

namespace App\Exceptions;

use Exception;

use Illuminate\Auth\AuthenticationException;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler

{

......

......

/**

* Convert an authentication exception into an unauthenticated response.

*

* @param \Illuminate\Http\Request $request

* @param \Illuminate\Auth\AuthenticationException $exception

* @return \Illuminate\Http\Response

*/

protected function unauthenticated($request, AuthenticationException $exception)

{

if ($request->expectsJson()) {

/** return response()->json(['error' => 'Unauthenticated.'], 401); */

$response = ['status' => 'error','message' => 'You pass invalid token'];

return response()->json($response);

}

return redirect()->guest('login');

}

}

You can do it Just.....


May 17, 2017 | 3467 Viewer | Category : Laravel

Related Posts: