3
votes

I am trying to create API with laravel passport authentication now it is very easy to make API with laravel passport. I am using personal access token to create access token for API users. As my client and server are both one, but when token not provided in the API it redirect to login page create by laravel auth scaffold php artisan make:auth, I want to return json response with message "Token not provided."

https://laravel.com/docs/5.4/passport#personal-access-tokens

I am using auth:api in routes.

How to pass json response for API if token not provided?

2
anyone have solution for this?Mahesh B

2 Answers

8
votes

I also encountered this same issue. To solve that redirection, you have to pass an extra parameter into the header of the request:

Accept        application/json

Now, it will return JSON response instead of redirection to the login page.

So now with an invalid request, it will return JSON response like: {"error":"Unauthenticated."}

But there is no easy way to customize the passport responses. I'm searching some standard way, but didn't get any yet.

0
votes

I also encountered this same issue. To solve that redirection, you have to pass header of the request of json response. for that i made decision to make middleware as below

public function handle($request, Closure $next)
{
    $request->headers->set('Accept', 'application/json');
    return $next($request);
}

the above middleware will force the header to add json response, group the api collection as below

Route::group(['middleware' => 'json.response'], function () {

 //your routes here

});