我尝试使用OAuth进行身份验证,计划使用PHP和cURL。第一步是检索"代码" e.g:
fd7d5f6cde6c47e4a86ba28b22ac4583
之前我使用过Twitter API,它的工作方式也类似。我将代码交换为access_token
然后我可以进行身份验证。
问题在于,验证的方法是点击窗口上的按钮,说明"我允许"。这是那个窗口:
我的问题:有没有办法在不需要点击此网址的情况下执行此操作?
例如,有没有办法让我使用我的脚本自动执行此过程?当我使用Twitter时,我能够使用cURL转到此链接并传递身份验证,然后检索此代码。
这是仅由我使用的项目的一部分,基本上用于检索我自己最近的instagrams。我不希望访问我网站的访问者必须点击"授权"每次他们出现。
目前我只是这样做,是否有什么可以添加到网址以自动授权?
$auth_request_url = 'https://api.instagram.com/oauth/authorize/?client_id='.$client_id.'&redirect_uri='.$redirect_url .'&response_type=code';
/* Send user to authorisation */
header("Location: ".$auth_request_url);
以下是代码有效的示例,但仅一次:
$url = "https://api.instagram.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirect_url,
'code' => $code
);
$curl = curl_init($url); // we init curl by passing the url
curl_setopt($curl,CURLOPT_POST,true); // to send a POST request
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters); // indicate the data to send
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // to stop cURL from verifying the peer's certificate.
$result = curl_exec($curl); // to perform the curl session
curl_close($curl); // to close the curl session
$arr = json_decode($result,true);
我手动从URL末尾获得了$code
。但它在一次使用后到期。因此,每次我想执行脚本时,我都需要弄清楚如何运行和检索$code
。
答案 0 :(得分:4)
只有在客户第一次询问用户时才需要批准,并且无法避免这种情况。您正在从最终用户那里获取信息,如果客户可以从用户那里获得该信息或权限而无需至少一次明确批准,那么这将是一个巨大的安全漏洞。但在第一次之后,应该同意存储并重新使用您的客户。
答案 1 :(得分:2)
我知道这有点老了,但我想:
https://api.instagram.com/oauth/authorize/?client_id='.$client_id.'&redirect_uri='.$redirect_url .'&response_type=code';
之后
它会重定向到您的$redirect_url/?code=XXXXXXXXXXXXX
因此,您可以按$code = $_GET['code']