Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

farshadf's avatar

prevent any other application to call your rest api in laravel

i have an authentication sms api which send a code to user to insert and i authenticate or register user . now my problem is that someone is calling that api from the outside of my server to random numbers and causing me some charge .now i come up with this idea that i could block all the requests but from my own server . then i came across CORS and fruitcake/laravel-cors . after installing and configuring the package now i have this key in my header :

Access-Control-Allow-Origin https://mydomain.com/

i am seeing that in my response in postman . now i think i my self should not be able to call that in my post man but i can and it sends sms so i think if i can call it from local and post man why not some one else . is that true and my problem yet exists ? or i solved that with that header which was added to request ?

0 likes
25 replies
automica's avatar

@farshadf I’ve got an api that only I want to use myself and I restrict access by passing an access_token in the header and then checking it via a custom middleware.

Whilst that won’t stop people trying to hit your api, it will certainly limit their success.

1 like
farshadf's avatar

i am a bit confused . you mean that from vue i have to generate a jwt token and pass it in api header ?? can you please explain a bit more . thanks

automica's avatar

@farshadf i didn't see you are in vue :P

for my app, I've defined a static token in my .env that i pass in as an argument into my vue component, add it to the header when make my axios call, and then check in backend that matches it against what's in the .env.

Whilst that's probably hackable if someone was to intercept the request on my frontend, its enough for me as i'm trying to stop someone spidering my api and then hitting it that way.

1 like
laracoft's avatar

@farshadf CORS won't solve your problem.

Think of the access_token as a "special" password.

For cost based API like SMS, it is a better idea to use server to server API, not browser to server.

1 like
automica's avatar

@laracoft from what i understand, the requests for SMS are being handled by @farshadf's api but he's having issue stopping other people from hitting it.

eg vue front end calls backend which then calls api service.

the access token is just a password.

laracoft's avatar

@automica I have the same understanding, but I don't think it is safe to put the "access_token" in vue. Hackers can still get hold of the token and abuse it. Using authentication and/or csrf token is the way to prevent abuse.

farshadf's avatar

yes right that's exactly my problem and your solution would solve this . thanks the answer and explanations it helped

automica's avatar

@laracoft

with authentication, you still need to pass a token. if this is a vue app (standalone) then you'll need to store the token somehow.

obv if its vue inside Laravel then csrf is a better option.

laracoft's avatar

@automica

Sure, there are many ways to skin the cat.

But since it is about abuse, I will want to make it impossible to abuse (unless they get through the authentication).

However, Vue will only make it harder.

1 like
farshadf's avatar

just for the record now that we talked about csrf i went to check the verifyCsrfToken.php and gues what i found one my team mates added this to the file :

 /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'api/*',
        'api/v1/*',
        'users/join/login',
        '/users/notification',
        '/users/social',
    ];

and i am sure that this is how they call my api and abuse it because i dont have a stand alone vue project and my vue is withing laravel . is that right ???

farshadf's avatar

well its api/* which i think its all my apis

farshadf's avatar

i think first i remove the api from exceptions of csrf and then place a token in .env and then call it in api header i think that would be fine to secure that twice :P so i guess i do both of your solutions

laracoft's avatar

@farshadf

api/* and api/v1/* is redundant because api.php route does not load the VerifyCsrfToken middleware. I suspect your colleague placed api/* routes in web.php (which is wrong).

It all boils down to not fully understanding the web vs api concept.

1 like
farshadf's avatar

well thanks if the Csrf is not the Answer here which is not because its Api then i think i should stick to the token and pass it in header right ??? i am a bit confused because i dont know how to authenticate the user because its an step before registration .

laracoft's avatar

@farshadf let's forget about everything first.

  1. To stop abuse of SMS sending, I think a good way is to use credentials
  2. Will you store the credentials in HTML? (storing in Vue is equivalent to storing in HTML)
  3. Or will you use PHP to write a login page and only after login you will allow user to send SMS? (CSRF, technically not CSRF, but we use that to keep things simple for now)
1 like
automica's avatar
automica
Best Answer
Level 54

@farshadf you aren't going to be able to do it via authentication then.

I added a new middleware

<?php

namespace App\Http\Middleware;

use Closure;

class VerifyAPIAccess
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (
            !(App::environment('local'))
            && (
                !$request->header('access-token')
                || $request->header('access-token') !== env('APP_API_TOKEN')
            )
        ) {
            return response()->json(['Message' => 'You do not access to this api.'], 403);
        }

        return $next($request);
    }
}

and then added to my route

Route::group([
    'middleware' => [
        VerifyAPIAccess::class,
 	'throttle:60,1'
    ]
], function () {

// list some routes

});

you could also restrict access by adding throttling which would stop someone from hammering your API, with token or not.

2 likes
automica's avatar

@farshadf as you haven't got an authenticated user yet, it is still possible to use CSRF as that's a 1 time token refreshed at every request that Laravel backend knows is being passed from the front end.

you can just add VerifyCsrfToken to your middleware and disgard using a custom middleware (as I previously supplied)

1 like
farshadf's avatar

@laracoft thanks but i cant use this as my company needs the user to insert mobile number first step send a verification code and then register him and that person is using this api to send some messages to some random numbers so i think i cant use laravel default and sms verification after register method .

farshadf's avatar

thanks man i think this solution of middle ware is the best for now to keep it simple and safe though as others said it may not be completly secure but its fine for now . but this question remains in my head and i have to search about it that :

1-are all apis public and anyone call them to use them for any purpose as we said apis doesn't have CSRF protection

2-is there any offical way on documentation to protect apis from being called from out side .

any way @laracoft @michaloravec @automica i thank you all for helping me in this topic i really appreciate that time <3

laracoft's avatar

@farshadf create a route, /verify/mobile/+15558888 to send the authentication SMS to +15558888 , this way, no abuse.

Please or to participate in this conversation.