framework: auth:api not working - Redirecting to login page in Postman
I have an Laravel app wherein, my routes file looks like below, but whenever I send a Postman request to store.customer.complaint, I am redirected to the login route rather than sending an unauthorized response :
Route::get('/login', function () {
return 'Login';
});
Route::group(['prefix' => 'api/v1'], function () {
Route::group(['prefix' => 'customer'], function () {
Route::post('register', ['as' => 'register.customer', 'uses' => 'Api\Customer\CustomerController@store']);
Route::post('login', ['as' => 'login.customer', 'uses' => 'Api\Customer\CustomerController@login']);
Route::group(['middleware' => 'auth:api'], function () {
Route::post('complaint', [
'as' => 'store.customer.complaint',
'uses' => 'Api\Customer\ComplaintController@store',
]);
});
});
});
Postman Screenshot

About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 2
- Comments: 19 (3 by maintainers)
Send
Accept: application/jsonwith PostmanI personally for convenience use ForceJson middleware for all api routes:
With respect, this is not a laravel bug, thus we’re closing it. Our GitHub is not a support forum.
Laravel shoud separate API layer from View layer. Its is very confusing. I cant consume default behaviour becouse i am creating Laravel API and i dont have any Views
@GrahamCampbell Say this is not a bug?! This little presumption in code bugged me an hour to find and I now have to find a way to gracefully shut it up.
Why am I forced to accept to redirect to
'login'even if I don’t, and explicitly said so in theRedirectTofunction? Worst of all, in the process of raising an exception, The Exceptions are meant for the programmer to catch and figure out what’s what. I am working on a REST API, but not all users gonna be respectful and sendAcceptand my API is not going to send them only JSON.This what solved my problem after trying a lot of other ways.
I found top answer here helpful: https://stackoverflow.com/questions/45015586/laravel-request-expectsjson/57758245
@rkgrep Yes, you were correct, I sent an Accept header, it worked. Thanks for the tip 😃
@GrahamCampbell Sorry for the trouble as it was my mistake
I just realized, it is not
Accept, butContent-typeheader, you nee to addAcceptanywayOk. I see now. It is not provided in Laravel. You need to modify the middleware and add
$request->wantsJson()condition manually.