I'm building on Laravel 5.4 and trying to make a post request with postman, I have added the csrf token and just passing something as id.
I'm still getting TokenMismatchException in VerifyCsrfToken.php (line 68)
So here's my Postman:
I tried both X-CSRF-TOKEN and _token as headers.
I tried to put them as form-data and x-www-form.
nothing is working right for me in postman, yet in laravel my view and ajax are launching all good, but I need to work with postman on this.
Someone mentioned Postman Interceptor but after downloading it and turning it on both postman and browser... and well, nothing really happens, other than watching all the XHR that goes through my browser to include my request. Any leads on this? :)
always you can stop csrf for some route like admin you can do this throw open middleware and VerifyCsrfToken
And write any route in
protected $except = [
'admin/*'
];
OR
You can remove \App\Http\Middleware\VerifyCsrfToken::class, from array $middlewareGroups in App\Http\Kernel class.
if you're using token you can try setting the token in the auth tab with bearer token and the other parameters like "id" on body tab
Related
I try to access by wrong token in sanctum laravel but it return
The GET method is not supported for this route. Supported methods: POST instead of message: unauthorized. how can I solve this ?
This is my api route:
This is my controller:
and this is my result:
First of all, you talk about token, maybe you meant JWT, which is for REST and/or JSON Web-API, and normally does not allow "get" as access-method.
Your error-message simply means that the way you try to make the request is not allowed.
Hence, either allow it by replacing:
Route::get('my-url')-> ...
With:
Route::match(['get', 'post'], 'my-url')-> ...
Or change your request to make a Post request instead of a Get request.
Example how to change?!
If you did send us an example how you make a request, we could provide you how to do it right.
I've got a basic Laravel API that I'm trying to set up. I've set up a CORS middleware, and I'm making requests to the API from a different (local) domain (i.e., aaa.host is a React front-end making Axios requests to a bbb.host Laravel API back-end).
All GET requests successfully go through the API and return a response, but any POST requests I attempt fail. My understanding is that the CSRF token is only required in Laravel for web requests, not API requests. As such, I can't understand what I'm missing and why POST requests aren't going through. If I change a POST route to a GET route, it instantly works, so the fact that it's a POST route seems to be the issue.
Here's an example of what the failed POST request looks like in the Chrome console:
I've looked at the Laravel API docs, but I don't understand what I'm missing. Does anyone have any ideas? Also, for what it's worth, I'm using Laravel 5.8.29. Thank you.
Edit: Here's what routes/api.php looks like:
Route::middleware(['cors'])->group(function () {
Route::post('/missing-subpath-on-purpose/item/create', 'SomeController#createItem');
});
Again, if I change Route::post to Route::get and make an Axios GET request instead of a POST, it works fine.
Many thanks to nice_dev for identifying the real problem and helping me solve it. Turns out that the Laravel API was fine and sending POST requests to it from Postman worked fine.
The issue was with the browser itself. If you send a POST request with a Content-Type of application/json, the browser will force two requests to occur, which was causing all sorts of problems. (I don't know at the moment the reasons for this, but I'm sure browser-makers have their reasons for doing things this way.)
Nevertheless, by changing the default Content-Type for all Axios requests in the browser to application/x-www-form-urlencoded, it solved my problem. Thank you.
Edit: After playing around with this more, I realized that I did want to be making application/json requests, but doing so was causing the aforementioned issues with CORS.
To fix this, I created the following CORS middleware in Laravel:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next) {
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Origin: *');
return $next($request);
}
}
I then added it to the global middleware in Kernel.php as follows:
protected $middleware = [
..., // Other middleware here.
\App\Http\Middleware\Cors::class,
];
The mistake I had made is that the CORS middleware wasn't part of the global middleware, but the route middleware, which was causing the issues.
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.
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
...
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.
I'm new to laravel and sorry for the silly question I've posted a request via postman with two parameters,In my routes api.php file,
Route::post('/mail', 'TripsController#mail');
with header,
Accept:application/json
And exclude the token verify in VerifyCSRKToken as,
protected $except = ['api/*',
];
and my url:
http://localhost/Movecabadmin/api/mail
It returns the message as {"message":"Unauthenticated."}
Question 1:Is I need to pass any authentication value with the request?If it is then How?
Question 2:How to get the passed parameters in my controller?
You are getting this {"message":"Unauthenticated."} because the Route::post('/mail', 'TripsController#mail');
going under some kind of authentication or middleware.
Remove that and you will get your desired result.
I am working on an Android laravel application, but I have this road problem ?? Route::post('register','Api\Auth\RegistrationController#register');
Most likely you are trying to make a GET request on POST-only route. Check your route file.
Have you put
protected $except = [
'Api/*'
];
in your VerifyCsrfToken.php file? As far as I know, APIs typically use tokens to authenticate users and do not maintain session state between requests. So try this and check your headers and body for API post request.