Issue
I am using Laravel API authentication with a token. (as explained here: https://laravel.com/docs/5.8/api-authentication#protecting-routes)
I am running some tests with Postman and it works fine. When I try to access the route without a valid token, I see that the response is the (html of the) login page of my app. How can I return a Unauthorized
message instead of the complete login page? Do I have to create a custom middleware?
Controller
class ExampleController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
public function show(Request $request) {
return response()->json($request->user()->name);
}
}
Solution
Please add the method in the class Handler in the file location app/Exceptions/Handler.php
/**
* 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);
}
return redirect()->guest(route('login'));
}
And also add the following line above the class in the same file as mentioned above: use Illuminate\Auth\AuthenticationException;
In the postman within the headers section please add the following header : X-Requested-With:XMLHttpRequest
Hope this helps and resolves the issue. Thanks.
Answered By - Saibal Roy
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.