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

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);
}

Related

Remove token in frontend using Vue JS after deleting it from database in backend with Laravel?

I'm developing an application with Vue 3 and Laravel 9.
I did all login, registration and logout. However, I had an idea to keep the session unique per browser. I delete all tokens on user login if they exist. That way I can have front-end control with just one session open per browser, as I've already done this logic there.
The problem knowing the ways I can remove the token on the front-end to logout/redirect the user to login, after receiving the "Unauthenticated". For I check the vue routes with the token in localStorage.
Remembering, I'm using sanctum.
I'm looking for procedures. However, I'm afraid of doing something wrong, as I wonder about data security and vulnerabilities, as these processes of building a software require caution and a lot of testing.
I'm not sure if i got the question right, but you would normalle use an axios interceptor like so:
_axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
console.log('Intercept: 401 - Unauthenticated')
//DELETE THE TOKEN FROM STORAGE AND FROM AXIOS HEADER
delete window.axios.defaults.headers.common.Authorization
localStorage.removeItem('token')
return router.replace({ name: 'login' })
}
if (error.response.status === 403) {
console.log('Intercept: 403 - Unauthorized')
}
if (error.response.status === 422) {
console.log('Intercept: 422 - Validation Error')
}
return Promise.reject(error)
},
)

Laravel 8, trying to check if user has been verified during login returns an error

I am using laravel 8 in combination with vue and I am trying show an message when a user that tries to login before this user has verified his/her emailaddress.
// loginController.php
if (Auth::attempt($credentials)) {
if (Auth::client()->verified != 1) {
//good
}else{
// bad, message users needs to verify email first
}
}else{
//login not correct try again
}
Now I am getting this error
Access to XMLHttpRequest at 'http://localhost:8000/home' (redirected from 'http://localhost:8000/api/login') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

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);
}

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

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.

How can I insert an interceptor with AngularJS to redirect to login page?

I have a login system that will hold the session for 2 hours. After 2 hours, when the client makes API calls, they get back an error:
{
"Success": false,
"Error": {
"ErrorCode": "002",
"ErrorMessage": "Session expired"
}
}
I need to then redirect the client to /login when that happens. The problem is that I get that error from individual API calls, so rather than change EVERY API call, is it possible to have a global interceptor?
Following the example for Interceptors found here, you can do something like the following in the response section of the interceptor:
response: function(resp){
// resp.data will contain your response object from the server
if(resp.data && !resp.data.Success){
// check for error code
if(resp.data.Error && resp.data.ErrorCode === '002'){
$location.path('/login');
return $q.reject(resp);
}
}
return resp || $q.when(resp);
},
This is assuming that your server is returning a 200 when you get this error message, not on a 401 or 403, but that's what it looks like you're doing. Hope that helps.

Resources