how to fix bug laravel validator with Post man send API. Validator return redirect uri root path. it not errors json status 422 - laravel

how to fix bug laravel validator with Post man send API. Validator return redirect uri root path. it not errors json status 422.
Laravel redirect to root on request validation error .
I have a required field in a Laravel Request Class and when that field is not present in the request, the request is redirected to root '/'.
I am sending the request via Postman.

Please add Accept: application/json in you header.

Laravel redirect validator root url "/" by it check ajax == false. if it return true, it run
If ($ this-> expectsJson ()) {
             Return new JsonResponse ($ errors, 422);
         }
I solved the problem by adding setup POST MAN in Headers:
I hope it will be useful to the next person when the validator does not work as you expect, you need to set it up like sending ajax to the routes api:
"Key" => "value"
X-Requested-With => XMLHttpRequest
Post Man need config setting some ajax
Otherwise laravel will not be able to return error code 422.
If ($ this-> expectsJson ()) {
             Return new JsonResponse ($ errors, 422);
         }
==> return false if not have "X-Requested-With" : "XMLHttpRequest" in headers POST MAN.
ajax or not ajax active other #.
sorry i do not know english.

Related

how to control 405 response in laravel 8 and passport without token access front insomnia

I am building an API (my first api in this framework) in laravel 8 with passport 10 for accesses by token, to consult and test the API I use Insomnia, in insomnia I do the work environment with two variables "base" for the URL and "token".
When I test my API routes from Insomnia and pass the Token, it does not give me problems, the errors start when I remove the environment variable Token in Insomnia, the laravel API crashes with a 405 error (Method not Allowed).
My question is how can I control laravel so that when the user doesn't send the token my application doesn't crash?
I insist, this only happens when I remove the Token environment variable in Insomnia.
Thank you
First, i want to make sure that you are sending the Accept and Content-Type.
Accept: application/json
Content-Type: application/json
Second, MethodNotAllowedException indicates that you calling the route with different HTTP verb as you can see supported method is POST and you are using GET.
Third, in order to catch the MethodNotAllowedException you can add in your Handler.php located at app\Exceptions\Handler in report method
public function render($request, Throwable $e)
{
if ($request->ajax() && $e instanceof MethodNotAllowedException) {
return response()->json([
"Please enter your token"
], 405);
}
return parent::render($request, $e);
}

Laravel - How to catch "HttpExceptions", because of POST request when CSFR is wrong?

So the User logs out on one tab and on the other tab he is "visually" still logged in.
Now, for example, the user sends a Chat message via POST route, but the server responds with:
Request Method: POST
Status Code: 419
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
The reason is that the CSFR Value is false, because the User is logged out.
My wish is to have the same response like in GET Request Methods.
There I get:
Request Method: GET
Status Code: 401
message: "Unauthenticated."
Because the User is not authenticated anymore. (Middleware is set to 'auth')
Why do I need this?
I want to catch failures with axios and check if the user is unauthenticated. If so the page is reloaded.
But right now I don't know if the user is unauthenticated or if he tries to exploit my page, but has a wrong csrf token.
Current solution in Handler.php
if ($exception instanceof TokenMismatchException){
return $request->expectsJson()
? response()->json(['message' => 'Invalid CSRF.'], 400)
: abort(400);
}

CSRF Token Name on Django Documentation is not Matching the Actual Name of the Variable in AJAX Header

I was struggling to send and recieve CSRF token, and I found, in the end, that Django was not able to get the token value because its name was different from the recommended one in its documentation. Why?
(I am doing AJAX on a HTTPS address and requests are cross-site.)
Django documentation recommends that I add token to AJAX header in following way:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Here, the name is X-CSRFToken, which somehow becomes HTTP_X_CSRFTOKEN.
On the other hand, Django is looking up the cookie under CSRF_COOKIE.
Line 278 in csrf.py of CsrfViewMiddleware:
csrf_token = request.META.get('CSRF_COOKIE')
if csrf_token is None:
# No CSRF cookie. For POST requests, we insist on a CSRF cookie,
# and in this way we can avoid all CSRF attacks, including login
# CSRF.
return self._reject(request, REASON_NO_CSRF_COOKIE)
I cannot change the variable name because I get this error:
Request header field CSRF_COOKIE is not allowed by Access-Control-Allow-Headers in preflight response.
So, I ended up changing the variable name in the source code from CSRF_COOKIE to HTTP_X_CSRFTOKEN. Are there any way to make this work?
(I do not do #csrf_exempt, so please do not recommend.)
The problem is not from Django, if you read closely here: https://docs.djangoproject.com/en/2.0/ref/csrf/#how-it-works you will understand how it works and what kind of logic they follow.
The problem is that you are not allowing the headers:
Request header field CSRF_COOKIE is not allowed by Access-Control-Allow-Headers in preflight response.
If you search for this ACAH you will find that you must edit your server config file to allow this kind of posts.
The other case is that you may not be sending properly the header and that's why it's looking for the cookie. In that case you can try adding this to your header:
xhr.setRequestHeader('X-CSRFToken': $('meta[name="token"]').attr('content') });

Yii2 CORS inserts two records

I am building an API with Yii2 and have enabled the CORS filter to handle requests from a web frontend which is working.
However because of the pre-flight OPTIONS request and then the real POST request I am getting two records added to the database, one for each request. I would have thought that Yii should accept the OPTIONS request, return the correct headers and then exit. Why does it actually process the full request?
I am working around this for now by adding this to the top of the controller action:
if(Yii::$app->request->getMethod() == 'OPTIONS') {
return;
}
Is that the best approach or am I missing something?
That should be wrong because a browser need the options response to know the allowed list of verbs he can send. Otherwise a 401 error may be raised. Its source code can be seen here:
class OptionsAction extends \yii\base\Action
{
public $collectionOptions = ['GET', 'POST', 'HEAD', 'OPTIONS'];
public $resourceOptions = ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
public function run($id = null)
{
if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
Yii::$app->getResponse()->setStatusCode(405);
}
$options = $id === null ? $this->collectionOptions : $this->resourceOptions;
Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $options));
}
}
And that is all what it does: sending a list of allowed verbs within a response headers.
Maybe the POST request has been sent twice from client script due to unexpected responses. Try to apply the answer I posted in your other question instead. I think it will also solve this:
Yii2 CORS with Auth not working for non CRUD actions.

ajax json request , always returning error

Hello i've got a problem with ajax json request. Im always getting an error, even if the requests are succeeded. At the moment i have this code:
function sumbitLoginForm(user, pass) {
if (user.trim() == '' || pass.trim() == '') {
alert("You must enter username and password!");
} else {
$.ajax({
type : 'POST',
url : 'https://url.php',
dataType : 'json',
data : {
userlogin : user,
userpass : pass
},
contentType: "application/json;",
success : function(data) {
$("#images").html("uspeshno");
},
error : function(data) {
$("#images").html("greshka");
}
});
}
return false;
}
$(document).ready(function() {
clearPageInputs();
$("#submitButton").click(function() {
sumbitLoginForm($("#username").val(), $("#password").val());
});
});
Im always getting an error , no matter what username and password i type . But the status of request is changing , if i type correct user and pass i get status 302 Moved temporarly , but when i type wrong user or pass i get status 200 OK . What am i doing wrong ?
PRG Pattern and Ajax
It looks like your server returns a HTTP 200 status code when the userid and password will not validate. This is proper behavior, as HTTP error codes not meant for application errors, but for HTTP protocol errors.
When the userid and password are matched succesfully, you are redirected to another page. This is also normal behavior, e.g. to prevent other people to re-use your login credentials using the back key.
This is called the Post/Redirect/Get pattern.
See: http://en.wikipedia.org/wiki/Post/Redirect/Get
The problem is that the PRG pattern does not play nice with Ajax applications. The redirect should be handled by the browser. It is therefore transparent for the jQuery code. The Ajax html response will be the page that is mentioned in the Location header of the 302. Your Ajax application will not be able to see that it is being redirected. So your are stuck.
In one of my projects I solved this on the server side. If I detected an Ajax call, I would not send a redirect but a normal 200 response. This only works if you have access to the server code.
If you cannot change the redirect for your Ajax calls, then you can parse the response headers or the html to see if you were being redirected and act accordingly. Probably the login will set a cookie, so you might try and look for the presence of that cookie.

Resources