How to securely access a protected API with Javascript through a php proxy?

0 投票
最新提问 用户: (120 分)

I have developed a jQuery Plugin that displays some data it gets from a secured RESTful API. The API is secured by basic authentication and a token. To not leak the basic authentication credentials nor the logic to create the token, I moved them to a proxy.php that basically looks like that:

$url = "http://the-api.com/path";
$context = stream_context_create(
    array(
        'http' => array(
            'header'  =>
                "Authorization:Basic " . base64_encode("$username:$password") . "\r\n" .
        )
    )
);
$response = file_get_contents($url, false, $context);

header("content-type: application/json");
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
header("Access-Control-Allow-Methods: GET, OPTIONS");
header('Access-Control-Allow-Headers: X-Requested-With, Origin, Content-Type, Authorization');
return $response;

It forwards the request with the necessary credentials and returns the response of the API. So far so good. The credentials are not in the Javascript Code. However, other people can just execute the same request by calling the proxy.php. How can I verify that only the jQuery Plugin can call the proxy.php successfully? Could it be done by a combination of cookie and token? The proxy.php is on the same host/domain as the jQuery Plugin.

发表于 用户: (140 分)
theres no way...
发表于 用户: (100 分)
You can protect that proxy.php only allowed ajax call. This SO question may can help you. stackoverflow.com/questions/1393904/ajax-only-access

1个回答

0 投票
最新回答 用户: (7k 分)

How can I verify that only the jQuery Plugin can call the proxy.php successfully?

You can't.

Anything you do to try to limit it will eventually boil down to "The browser makes an HTTP request". All the details of that HTTP request are available to the user of the browser (NB: The browser works for the user, not for the website). The user can copy those details and use them however they like.

Could it be done by a combination of cookie and token?

No. The cookie and the token could be copied because they are visible to the browser and thus the user.

欢迎来到 Security Q&A ,有什么不懂的可以尽管在这里提问,你将会收到社区其他成员的回答。
...