Reputation: 351
I'm trying to create REST API using Laravel. I'm using JWT (Tymon\JWTAuth) to authenticate users.
Here is part of my api.php file with /api routes:
Route::middleware('auth:api')->get("match/{id}", "ApiMatchController@getMatch");
Route::middleware('auth:api')->put("match/{id}", "ApiMatchController@editMatch");
Now, I'm sending GET request to /api/match/7
. Authorized user gets match details as expected. Unauthorized user is redirected to root url /
but I want user to stay on the url, I just want to return HTTP code 401 - Unauthorized. Where can I change this? I can do that inside of ApiMatchController@getMatch
method but I would like middleware auth:api
to do that for me. Is there any way how to do this?
Then, I'm sending PUT request to /api/match/7
with some data. Request from authorized user works just fine but unauthorized user now gets HTTP code 405 - Method Not Allowed (with debug info: Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: The PUT method is not supported for this route. Supported methods: GET, HEAD.
). Why? I cleared the route cache and as you can see, there IS a defined route in api.php. This behaviour really happens just with unauthorized user.
Upvotes: 2
Views: 1697
Reputation: 4534
I have tried the combination of authorize method under controller, and Throwable mentioned in laravel docs: https://laravel.com/docs/8.x/errors
try{
$this->authorize('create',Client::class);
} catch(Throwable $e)
{
echo $e->getMessage();
return false;
}
you can use same approach for your api responses.
Upvotes: 0
Reputation: 14281
About the first part:
Authorized user gets match details as expected. Unauthorized user is redirected to root url / but I want user to stay on the url, I just want to return HTTP code 401 - Unauthorized. Where can I change this?
This is because your default guard is web
, so in that case when a user tries to access a protected route it will be redirected to the home page (by default, this can also customized of course).
To change the default guard to api
go to config/auth.php
and change it like this:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
Note: When making HTTP Requests, add this headers:
/** The following tells Laravel that you want a response in json format. */
Accept: application/json
/** The following is for POST/PUT/PATCH requests, it tells the request payload format. */
Content-type: application/json
About the second part:
Request from authorized user works just fine but unauthorized user now gets HTTP code 405 - Method Not Allowed
PHP doesn't handle well the PUT
/PATCH
/DELETE
methods, in order to bypass this inconvinience do a POST request and then add a hidden _method
field to the form.
The value sent with the _method field will be used as the HTTP request method:
Request body (the method is case sentitive):
Endpoint:
/api/match/7
Headers:
Accept: application/json
Content-type: application/json
Payload or Body:
_method: PUT
...
Upvotes: 0