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

Bacherino's avatar

How can i access an external domain's api using bearer token ?

I'm trying to access another domain's api from my serrver using ajax post request but there's a handicap this request sending by my pc's external ip adress and there's a firewall rule my server's ip adress has been set so when i'm trying to access that api with below code part it throws me an 403 error. Am i using wrong solution by using ajax or is there a better solution for this situation?

$.ajax({
            url: 'domain.com',
            type: 'POST',
            
            data: {
                'user':'user',
                'pass':'pass'
            },
            crossDomain:true,
            dataType : 'jsonp',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', 'Bearer Token');
            },
            success: function (res) {
                console.log(JSON.stringify(res));
             },
            error: function (res) { 
                console.log(JSON.stringify(res));
            },
        });
0 likes
9 replies
tykus's avatar
tykus
Best Answer
Level 104

This client-side approach exposes your API credentials publicly; which might have implications with the availability of the service quota.

So, instead consider making an endpoint in your own application that is responding tot he AJAX request; and in that endpoint you control (i) the credentials and (ii) the service usage - through caching for example. Use the Laravel Http Client to make requests to the third party.

1 like
Bacherino's avatar

@tykus @webrobert also i have a 2nd question ;

Using sanctum or passport is a must or should in this kind of project or http client is enough for it ?

Bacherino's avatar

@tykus What if i use sanctum or passport instead of jQuery is could be better or not ?

Bacherino's avatar

The thing is i'm a newbie on laravel and this is my first project i want to learn best way to handling api with bearer token from another domain.

tykus's avatar

@Bacherino the best way is a matter of opinion. What I would suggest is never ever expose your credentials to your users (as would be the case in the OP). Keeping that information on the server like I described earlier is more secure assuming you take measures to cache, or rate-limit access to the third party API

1 like
webrobert's avatar

@bacherino,

What helped me was to think of api data as an alternate database. So instead of using a model to get the data that you load via a controller you get it via a service. So where your controller would get data to server up via a model instead use the service. Make sense? There are videos here on api. The video game series is simple. There is also a whole series on Laravel 8 from Scratch, that one is free.

1 like

Please or to participate in this conversation.