PHP:
<?php
if (!empty($_SESSION['user'])) {
header("Location: /account/earn/links");
}
$time = time();
$data = array();
$config = new config();
$ip = func::clear($_SERVER['REMOTE_ADDR']);
$meta =func::clear($_SERVER['HTTP_USER_AGENT']);
$vk_url = 'http://oauth.vk.com/authorize';
$vk_params = array(
'client_id' => $config->vk_client_id,
'redirect_uri' => $config->vk_redirect_uri,
'scope' => 'email,photos',
'response_type' => 'code'
);
$data['vk_auth'] = $vk_url . "?" . urldecode(http_build_query($vk_params));
if (isset($_GET['code'])) {
$result = false;
$vk_params = array(
'client_id' => $config->vk_client_id,
'client_secret' => $config->vk_client_secret,
'code' => $_GET['code'],
'redirect_uri' => $config->vk_redirect_uri
);
//ВОТ ДО СЮДА ДОХОДИТ, А ДАЛЬШЕ НЕ ИДЁТ***
$token = json_decode(file_get_contents('https://oauth.vk.com/access_token' . '?' . urldecode(https_build_query($vk_params))), true);
if (isset($token['access_token'])) {
$vk_params = array(
'user_ids' => $token['user_id'],
'fields' => 'user_id,first_name,last_name,photo_100',
'access_token' => $token['access_token']
);
$userInfo = json_decode(file_get_contents('https://api.vk.com/method/users.get?&v=5.0' . '?' . urldecode(http_build_query($vk_params))), true);
if (isset($userInfo['response'][0]['id'])) {
$userInfo = $userInfo['response'][0];
$result = true;
}
}
if ($result) {
$uid = $userInfo['id'];
$email = $token["email"];
$first_name = $userInfo['first_name'];
$last_name = $userInfo['last_name'];
$screen_name = $first_name . ' ' . $last_name;
$photo_100 = $userInfo['photo_100'];
$ref_1 = 0;
$db->Query("SELECT * FROM users WHERE uid = '{$uid}'");
$user_data = $db->FetchArray();
if($user_data['ban'] == '2'){
die(header('location: /ban'));
}
$db->Query("SELECT * FROM lider WHERE id = '1'");
$lider_data = $db->FetchArray();
$lider = $lider_data['user_id'];
$ref_1 = $lider;
$ref_2 = 0;
$ref_3 = 0;
if (isset($_COOKIE['referer']) && !empty($_COOKIE['referer'])) {
$ref = func::clear($_COOKIE['referer'], 'int');
$db->Query("SELECT * FROM users WHERE id = '{$ref}'");
if ($db->NumRows() > 0) {
$db->Query("SELECT * FROM users_ref WHERE user_id = '{$ref}'");
$ref_dat = $db->FetchArray();
$ref_1 = $ref;
$db->Query("UPDATE users SET refs = refs + 1 WHERE id = '{$ref_1}'");
}
}
$db->Query("SELECT id, uid FROM users WHERE uid = {$uid}");
if ($db->NumRows() > 0) {
$user = $db->FetchArray();
$id = $user['id'];
$_SESSION['user'] = $id;
$db->Query("INSERT INTO auth (user_id,ip,time,meta) VALUES ('{$id}','{$ip}','{$time}','{$meta}')");
$db->Query("UPDATE users SET email = '{$email}', screen_name = '{$screen_name}', photo_100 = '{$photo_100}', ip = '{$ip}' WHERE id = '{$id}'");
header('location: /account/earn/links');
} else {
if (isset($_COOKIE['httpref'])) {
$httpref = func::clear($_COOKIE['httpref']);
} else $httpref = '0';
$db->Query("INSERT INTO users (uid,email,screen_name,photo_100,ip,date_reg)
VALUES ('{$uid}','{$email}','{$screen_name}','{$photo_100}','{$ip}','{$time}')");
$id = $db->LastInsert();
$db->Query("INSERT INTO users_conf (user_id,httpref) VALUES ('{$id}','{$httpref}')");
$db->Query("INSERT INTO users_ref (user_id,ref_1,to_ref_1)
VALUES ('{$id}','{$ref_1}','0')");
$_SESSION['user'] = $id;
$db->Query("INSERT INTO auth (user_id,ip,time,meta) VALUES ('{$id}','{$ip}','{$time}','{$meta}')");
header('location: /account/earn/links');
}
}
}
$ok_url = 'http://www.odnoklassniki.ru/oauth/authorize';
$ok_params = array(
'client_id' => $config->ok_client_id,
'response_type' => 'code',
'redirect_uri' => $config->ok_redirect_uri
);
$data['ok_auth'] = $ok_url . '?' . urldecode(http_build_query($ok_params));
$fb_url = 'https://www.facebook.com/v2.11/dialog/oauth';
$fb_params = array(
'client_id' => $config->fb_client_id,
'redirect_uri' => $config->fb_redirect_uri,
'response_type' => 'code',
'scope' => 'email'
);
$data['fb_auth'] = $fb_url.'?'.urldecode(http_build_query($fb_params));
new gen('login', $data);
Содержание
- У кого-нибудь были проблемы с OAuth-токеном в Terraform? Система просто
- 6 ответов
- Похожие вопросы
- Описание ошибок протокола OAuth 2.0
- Ошибки конечной точки /authorize
- invalid_request
- unauthorized_client
- unsupported_response_tpe
- invalid_scope
- login_required
- Ошибки конечной точки /token
- invalid_request
- invalid_client
- invalid_grant
- unauthorized_client
- usupported_grant_type
- OAuth 2.0 — Error Response and Codes
- Complete Python Prime Pack for 2023
- Artificial Intelligence & Machine Learning Prime Pack
- Java Prime Pack 2023
- 400 Errors
- 401 Errors
- Регистрация и авторизация через VK API
У кого-нибудь были проблемы с OAuth-токеном в Terraform? Система просто
перестала принимать токен, при этом CLI его принимает, а попытка его обновить приводит к получению того же самого токена.
6 ответов
А у поддержки лапки.
дебаг в терраформе ничего интересного не показал?
А как использовать?
Error: Error while requesting API to create Yandex Cloud Container: *********************** rpc error: code = Unauthenticated desc = OAuth token is invalid or expired
Похожие вопросы
Привет! Вопрос не от разработчика, а от предпринимателя принимается сообществом к рассмотрению?
Мы в скором времени должны приступить к созданию SPA на React.js и Node.js. Сейчас имеем сервер в Yandex Cloud, на Ubuntu 22.04, с Node.js и React,js. А также купленный домен.
А на стороне реакта, и сервера, внутри, нужно что-то указывать?
Как сейчас сделать так, чтобы именно содержимое этой папки было доступно пользователю, когда он набирал домен в строке своей?
расскажите, пожалуйста, когда вертикальное масштабирование не справляется? условно, нужна машина 96 ядер, 576 рам, 8192 хдд, такая штука обойдётся в 210 тыс. рублей в месяц, т.
Кому-нибудь нужна бесплатная подписка Яндекс плюс на 2 месяца? Пишите в лс. Каждому лично дам собственный промокод одноразовый.
А никаких проблем с доступом до машин нет? По ssh за 3 минуты появилась только надпись using name, сам сайт на машине не виден.
Добрый день! А приходилось ли кому нибудь настраивать VPN туннель до сервиса в кубере?
Коллеги, а нет ли сейчас аварий с влиянием на Managed Service for Kafka ? (Версия 3.0) что то кластер не создаётся с настройками по умолчанию, сразу доступность — Dead
Вы все правильно пишите. Я не спорю. Я лишь подумал может у кого есть подобная проблема и решил ее. Или у кого то нет таких проблем и надо общаться с админами моими. Просто к.
Источник
Описание ошибок протокола OAuth 2.0
В данном разделе приводится описание ошибок, возникающих при выполнении запросов в рамках протокола OAuth 2.0 и OpenId Connect 1.0.
В случае возникновения ошибок сервер возвращает информацию в двух полях:
- error — код ошибки.
- error_description — описание ошибки.
Далее будет представлена информация по кодам ошибок.
invalid_request
В запросе не передан обязательный параметр, либо значения переданного параметра некорректно, либо параметр пристутствует в запросе несколько раз, либо весь запрос имеет неправильный формат.
Возможные причины
- Осутствие обязательных парамтеров в запросе ( client_id , redirect_uri , resource , response_type ).
- Переданы некорректные значения параметров (неправильный формат redirect_uri , resource ).
- Переданы незарегистрированные значения параметров (незарегистрированный resource ).
- Переданы неподдерживаемые значения параметров (неподдерживаемый response_mode ).
- Передано некорректное значение параметра id_token_hint .
- Маркер, указанный в значении параметра id_token_hint , невалиден.
- Сервер не настроен на обработку параметра id_token_hint .
unauthorized_client
Клиент с указанным в запросе идентификатором не зарегистрирован, отключен, либо клиенту запрещено получения маркера доступа в рамках данного сценария.
Возможные причины
- По переданному в запросе client_id не найдено зарегистрированных клиентов.
- Переданный в запросе client_id принадлежит заблокированному клиенту.
- Использованный в запросе redirect_uri не зарегистрирован для используемого клиента.
- Используемый сценарий не разрешен для используемого клиента.
unsupported_response_tpe
Тип ответа не поддерживается.
Указанный в запросе response_type не поддерживается.
Возможные причины
- В запросе указан параметр response_type со значениями отличными от
- code ,
- token ,
- id_token ,
- id_token token ,
- code id_token
- code token
- code id_token token .
invalid_scope
Неправильная область использования.
Указанный в запросе scope не зарегистрирован на сервере.
Возможные причины
- В запросе указан параметр scope , значение которого не зарегистрировано на сервере.
- В запросе указан параметр scope , заблокированный на сервере.
- Срели значений параметра scope указано больше одной области использования, требующей подтверждения.
- Переданные парамтеры dss_scope_params имеют неправильный формат.
login_required
Запрос не может быть выполнен в интерактивном режиме (с указанием параметра prompt со значением none ).
Возможные причины
- Запрос не может быть выполнен в неинтерактивном режиме, так как требуется аутентификация пользователя.
Ошибки конечной точки /token
invalid_request
В запросе не передан обязательный параметр, либо значения переданного параметра некорректно, либо параметр пристутствует в запросе несколько раз, либо весь запрос имеет неправильный формат.
Возможные причины
- Не удалось получить идентификатор клиента из запроса.
- Отсутствие обязательных параметров в запросе (для сценария обмена маркеров: subject_token , actor_token_type , resource , grant_type , refresh_token ).
- Переданы некорректные значения параметров ( resource ).
- Переданы незарегистрированные значения параметров (незарегистрированный resource ).
- Переданы некорректные значения парaметров (для сценария обмена маркеров: неправильный формат subject_token , actor_token ).
- Маркеры доступа, указанные в значениях параметров subject_token , actor_token , не действительны.
- Переданы неподдерживаемые значения параметров (для сценария обмена маркеров: неподдерживаемый тип subject_token_type , subject_token_type ).
- Сервер не настроен на поддержку сценария обмена маркеров.
invalid_client
Не удалось осуществить аутентификацию клиента.
Возможные причины
- Не удалось получить идентификатор клиента из запроса.
- Клиент с указанным в запросе идентификатором не зарегистрирован или отключен.
invalid_grant
Разрешение, используемое клиентом, не является действительным.
Возможные причины
- Не передан параметр password в сценарии с использованием учетных данных владельца ресурсов.
- Сервер не настроен на обработку сценария с использованием учетных данных владельца ресурсов.
- Не удалось аутентифицировать пользователя по переданным username и password .
- Сценарий с использованием учетных данных владельца ресурсов не может быть использован для данной учетной записи пользователя из-за включенной вторичной аутентификации.
- Не передан код авторизации в сценарии с кодом авторизации.
- Переданный код авторизации истек или не действителен.
- Переданный код авторизации был получен другим клиентом.
unauthorized_client
Клиент с указанным в запросе идентификатором не зарегистрирован, отключен, либо переданы неверные учетные данные клиента.
Возможные причины
- Используется тип учетных данных клиента, отличный от разделяемого секрета.
- Переданы неверные учетные данные.
- Переданные учетные данные клиента истекли.
usupported_grant_type
Неподдерживаемый тип разрешение.
Разрешение, используемое клиентом, не поддерживается сервером.
Возможные причины
- Передан тип разрешения отличный от
- code ,
- password ,
- urn:ietf:params:oauth:grant-type:token-exchange ,
- refresh_token .
Источник
OAuth 2.0 — Error Response and Codes
Complete Python Prime Pack for 2023
9 Courses 2 eBooks
Artificial Intelligence & Machine Learning Prime Pack
6 Courses 1 eBooks
Java Prime Pack 2023
8 Courses 2 eBooks
The authorization server responds with HTTP 400 or 401 status codes. Here, two cases take place, if an error occurs during the authorization. In the first case, the client is not identified or recognized. In the second case, something else fails in spite of the client being identified exactly. In such a case, an error response is sent back to the client as follows −
error_description − It is an optional human readable error description in a language specified by Content-Language header, which is meant for the developer and not the end user.
error_uri − It is an optional link to a human-readable web page along with information about an error that can be helpful for problem solving.
error − It is a set of predefined error codes.
Following is the description of error codes and equivalent HTTP status codes.
400 Errors
The following table shows 400 errors with description.
OAuth 2.0 only supports the calls over https.
If an unsupported version of OAuth is supplied.
If a required parameter is missing from the request.
When a given parameter is too long.
When an invalid client ID is given.
When an invalid request parameter is given.
When a response type provided does not match that particular request.
When a grant type is provided that does not match a particular request.
When an invalid request parameter is provided.
When the client is not given the permission to perform some action.
When the resource owner refuses the request for authorization.
This error displays an unexpected error.
401 Errors
The following table shows 401 errors with description.
Sr.No. | Error & Description |
---|---|
1 |
When the provided token expires.
When the provided token is invalid.
When the provided URI with the request does not match the consumer key.
When the provided client server is invalid.
When the provided token has either expired or is invalid.
Источник
Регистрация и авторизация через VK API
Пытаюсь реализовать регистрацию/авторизацию на своём сайте через соц. сеть. Не совсем понятен принцип работы и дальнейшая безопасность после авторизации.
Создал приложение, добавил JS VK к себе, добавил тот скрипт, что там прописан. Соединение проходит, возвращается ID, имя и т.д. (всё что запрошу). Но как мне записать что-нибудь в БД, чтобы потом определить, что этот пользователь зарегистрирован/авторизован? Никакого хэша, который я бы мог использовать в этих целях, не возвращается.
Конечно, я могу после авторизации и получения ответа через JS, отправить AJAX-запрос к себе на сервер с ответом, который вернул ВК, но как проверить со стороны сервера, что авторизация прошла успешно и это не злоумышленник подсунул левый ID?
Хочется сделать именно асинхронную авторизацию, чтобы после клика на кнопку проверились данные и прошла авторизация/регистрация, и при этом она была бы безопасной.
Смотрел серию уроков «PHP » Аутентификация через ВКонтакте» и читал другие темы по этим вопросам, но, в основном, везде рассматривается синхронная авторизация, где пользователь будет несколько раз перенаправлен на другие страницы сайта, а мне такой вариант не подходит. Допускаю только одно обновление страницы пользователя: только тогда, когда он уже авторизован/зарегистрирован. Всё остальное — в асинхронном режиме.
Опять же, могу отправить ID пользователя к себе на сервер в свой скрипт, но как проверить его? Ведь у меня не будет параметра code , как в примере по ссылке выше и, соответственно, я не смогу отправить запрос для получения access_token .
Поправка: параметр code нашёл, а вот параметра redirect_uri — нет, и VK отвечает так:
Делаю запрос так:
$params = array( ‘client_id’ => ‘тут ид моего приложения’,
‘client_secret’ => ‘тут ключ моего приложения’,
$token = json_decode(file_get_contents(‘https://oauth.vk.com/access_token’ . ‘?’ . urldecode(http_build_query($params))), true);
Понял, что процедуры серверного получения code не избежать. Начал делать по этим инструкциям: https://vk.com/dev/auth_sites
Предварительно всё равно провожу клиентскую авторизацию и только при успехе отправляю запрос на сервер, который затем отправляет запрос для получения переменной code , но опять вылазит окно с требованием ввести логин/пароль VK (на этот раз его требует серверная авторизация), а не нормальный ответ. В качестве redirect_uri указываю адрес вызываемого AJAX-файла, надеясь, что сервер VK вернёт туда $_GET[‘code’] , и следующем запросом я смогу уже получить access_token .
Я так понимаю, окно с повторной авторизацией вылазит потому, что идёт проверка IP, которые не совпадают. Как быть?
Не понимаю, почему бы не сделать один и тот же code -ключ при клиентской авторизации и при серверной, чтобы можно было связать воедино и добиться-таки доступа в одно обновление страницы пользователя (с вылезающем окном VK, это ничего), но не 3-4 редиректа, как предлагается при полностью серверной авторизации в документации. Или, может, что-то делаю не так (что вероятнее).
Начал в PHP-файле делать так:
Теперь возвращается code при прямом открытии PHP-файла, а если он вызывается AJAX`ом, то там, понятное дело, ошибка после редиректа:
Попытка использовать cURL или file_get_contents приводит к тому, что возвращается форма авторизации ВК и начинает «скакать» в прямом смысле слова на экране.
Эх 🙁 Продолжаю разбираться. Может есть способ отправить запрос VK, но чтобы тот не редиректил назад, а вернул только ответ? (без redirect_uri сразу возращает ошибку)
UPD
Разобрался почти со всем самостоятельно: пришлось отказаться от авторизации «в один клик» и смириться с неизбежным — двумя редиректами сначала за code , а потом за access_token . Теперь другая проблема — как разлогинить приложение у пользователя?
А то получается, после одного подтверждения пользователем всё сохраняется и больше пользователя уже никто не спрашивает, разрешает ли он доступ сайта к данным, или нет. С одной стороны — это удобно, но с другой — у пользователя ведь может быть несколько учётных записей VK, или за одним компьютером могут сидеть несколько человек.
Поэтому нужно дать возможность разлогинить приложение у пользователя, например, при переходе по ссылке. Как я понял, это делается по ссылке
Но там ещё требует хэш, который непонятно откуда брать: в документации ни слова про разлогин. Техподдержка вконтакте молчит. Может хоть тут помогут?
Я пытался по-всякому передавать туда и code -переменную из авторизации, и access_token — толку нет, всё время:
Источник
Adblock
detector
Sr.No. | Error & Description |
---|---|
1 |
Here we list the most common errors encountered in Rabobank OAuth 2.0 flow on the client side. These use cases list reason for errors and how to troubleshoot them.
During the Authorization call to get the consent of the user, the TPP may encounter the following:
Invalid client id supplied
You receive an HTTP response of 401 Unauthorized with the message invalid client id or secret while invoking an Authorization flow.
This could be caused by one of the following:
- Invalid client id is supplied in the request.
- Your TPP application is not subscribed to an API using OAuth 2.0.
To solve this issue, your application should be subscribed to an API using OAuth 2.0 and provide a valid client ID.
Redirect URI mismatch
When registering an application, you should provide a redirect URI on the Rabobank developer portal.
If you have more than one redirect URLs listed in the developer portal, make sure to provide one of the redirect URI (as provided during registration) in the redirect_uri
query parameter during an Authorization call. If the redirect URI from your request does not match with the one registered on the Rabobank developer portal, you get the following error:
Requesting access token
To access the requested resources, you should exchange the received authorization
code
for an access token. During the retrieval of the access token, you may encounter the following:
Invalid authorization code (grant type code flow)
The authorization code should be sent to the token endpoint to get the access token. Sending an invalid authorization
code (expired, invalid, or already used) results in the below error:
Http status:
400
(Bad request)
{
"error"
:
"invalid_grant"
}
To avoid this error, you should pass the correct authorization
code before it expires (expiry: 5 minutes). Make sure to not call the token endpoint multiple times using the same authorization
code.
Adding a slight delay of 1000ms before calling this endpoint ensures that the authorization
code is in sync across our servers.
Invalid refresh token
Sending invalid Refresh token to get access token results in the below error:
Http status:
401
(Unauthorized)
{
"error"
:
"invalid_grant"
}
The Refresh token is valid for 30 days and can be only used once. To avoid this error, you should pass a valid Refresh token and not use the same token multiple times.
Invalid authorization header
While making a call to the token
endpoint, an Authorization header should be provided consisting of a client id and client secret. If an invalid combination is passed, it results in the below error:
Http status:
401
(Unauthorized)
{
"error"
:
"invalid_client"
}
To avoid this error, you should use the correct client id and client secret and make sure that the Authorization header is prepared as specified in the OAuth documentation.
Grant type missing
While making a call to the token
endpoint, the grant_type
query parameter should be provided. The value of this query parameter is based on the type of authorization you are passing to the endpoint.
For example, if you are swapping an authorization code for an access token the value of the parameter should be the authorization_code
.
An example of the error message returned is as below:
Http status:
400
(Bad request)
{
"error"
:
"invalid_request"
}
To avoid this error, make sure to provide all the required parameters, including grant_type.
Requesting resources with an access token
Access token invalid
The Access token issued by the authorization server is valid for 60 minutes for PSD2 and 24 hrs for Premium after receiving. Passing an expired or invalid Access token while accessing the resource results in the following error.
{
"httpCode"
:
"401"
,
"httpMessage"
:
"Unauthorized"
,
"moreInformation"
:
"This server could not verify that you are authorized to access the URL"
}
To avoid this error, you should always check the expiry time associated with the access token. If the token is expired, use a Refresh token to receive a new Access token.
If you are unable to get a new access token using the refresh token, it could be because the user consent is either expired or revoked. You can validate the consent using the Consent Details Service API.
If this is the case, you should renew the consent before proceeding.
How to check if the user consent is expired (or) revoked?
Using the information you received during the authorization flow, you can retrieve the consent by a specific Id as explained in the API Consent Details Service documentation.
If the consent status is one of the following, the consent is not valid and cannot be used to access the resources:
- expired
- revokedByPsu
- terminatedByTpp
- received
- rejected
Using an invalid consent results in the following error:
{
"httpCode"
:
"403"
,
"httpMessage"
:
"Forbidden"
,
"moreInformation"
:
"CONSENT_INVALID"
}
To access the resource gain, you should follow the authorization flow again and ask the user permission(s) to the required resources.
Deactivated or Expired consent
The consent of the user may be expired or revoked by the user, while your access/refresh tokens are still active, this results in a 403 Forbidden CONSENT_INVALID error message.
You may also check the status of the consent by making a call to Consent Details Service API and re-initiate the consent flow if required.
Not having the required permission to access an API
{
"httpCode"
:
"403"
,
"httpMessage"
:
"Forbidden"
,
"moreInformation"
:
"FORBIDDEN"
}
A 403 Forbidden FORBIDDEN error can be triggered if the Access token included in the request does not contain the correct scope for the API being used.
Example: You have an access token for the scope paymentRequest
, but you are trying to access the Account information API, this API requires a different scope: ‘ais.balances.read’.
To avoid this error, follow the authorization flow with the correct scope required for your API.
перестала принимать токен, при этом CLI его принимает, а попытка его обновить приводит к получению того же самого токена.
russian
software
database
yandex-cloud
14:56 29.03.2022
6
ответов
А у поддержки лапки.
14:57 29.03.2022
дебаг в терраформе ничего интересного не показал?
14:57 29.03.2022
че пишет-то?
14:59 29.03.2022
А как использовать?
14:59 29.03.2022
Nikolay 🤦♂️ Matrosov
че пишет-то?
Error: Error while requesting API to create Yandex Cloud Container: *********************** rpc error: code = Unauthenticated desc = OAuth token is invalid or expired
15:00 29.03.2022
Котяй Негодяй
А как использовать?
https://www.terraform.io/internals/debugging
15:01 29.03.2022
Похожие вопросы
I’ve been using code based on Jon Hurlock’s Twitter Application-only Authentication App for over a year now with no problem, and about 2 days ago it started returning this error when trying to generate a bearer token:
Invalid or expired token, code:89
My code is slightly altered to force it to check for SSL, since the page is not on an SSL-enabled domain. I have curl pull in the latest cacert.pem file.
This is application level oauth, NOT individual person oauth. So each time a call is made I generate a bearer token, make an API call, and then invalidate the bearer token. You can see his original code here (I pulled the latest version for the part I use): https://github.com/jonhurlock/Twitter-Application-Only-Authentication-OAuth-PHP/blob/master/Oauth.php
THis is the code used to get a bearer token. Note I only have to include the Application’s key and secret, there is no user involved and a user never has to allow the app nor authenticate it:
// Step 1
// step 1.1 - url encode the consumer_key and consumer_secret in accordance with RFC 1738
$encoded_consumer_key = urlencode(CONSUMER_KEY);
$encoded_consumer_secret = urlencode(CONSUMER_SECRET);
// step 1.2 - concatinate encoded consumer, a colon character and the encoded consumer secret
$bearer_token = $encoded_consumer_key.':'.$encoded_consumer_secret;
// step 1.3 - base64-encode bearer token
$base64_encoded_bearer_token = base64_encode($bearer_token);
// step 2
$url = "https://api.twitter.com/oauth2/token"; // url to send data to for authentication
$headers = array(
"POST /oauth2/token HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: Twitter App-Only Search",
"Authorization: Basic ".$base64_encoded_bearer_token,
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8"
);
$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL,$url); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_POST, 1); // send as post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, True);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, "/directory/path/cacert2014.pem");
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$header = curl_setopt($ch, CURLOPT_HEADER, 1); // send custom headers
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$retrievedhtml = curl_exec ($ch); // execute the curl
curl_close($ch); // close the curl
I’ve been using code based on Jon Hurlock’s Twitter Application-only Authentication App for over a year now with no problem, and about 2 days ago it started returning this error when trying to generate a bearer token:
Invalid or expired token, code:89
My code is slightly altered to force it to check for SSL, since the page is not on an SSL-enabled domain. I have curl pull in the latest cacert.pem file.
This is application level oauth, NOT individual person oauth. So each time a call is made I generate a bearer token, make an API call, and then invalidate the bearer token. You can see his original code here (I pulled the latest version for the part I use): https://github.com/jonhurlock/Twitter-Application-Only-Authentication-OAuth-PHP/blob/master/Oauth.php
THis is the code used to get a bearer token. Note I only have to include the Application’s key and secret, there is no user involved and a user never has to allow the app nor authenticate it:
// Step 1
// step 1.1 - url encode the consumer_key and consumer_secret in accordance with RFC 1738
$encoded_consumer_key = urlencode(CONSUMER_KEY);
$encoded_consumer_secret = urlencode(CONSUMER_SECRET);
// step 1.2 - concatinate encoded consumer, a colon character and the encoded consumer secret
$bearer_token = $encoded_consumer_key.':'.$encoded_consumer_secret;
// step 1.3 - base64-encode bearer token
$base64_encoded_bearer_token = base64_encode($bearer_token);
// step 2
$url = "https://api.twitter.com/oauth2/token"; // url to send data to for authentication
$headers = array(
"POST /oauth2/token HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: Twitter App-Only Search",
"Authorization: Basic ".$base64_encoded_bearer_token,
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8"
);
$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL,$url); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_POST, 1); // send as post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, True);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, "/directory/path/cacert2014.pem");
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$header = curl_setopt($ch, CURLOPT_HEADER, 1); // send custom headers
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$retrievedhtml = curl_exec ($ch); // execute the curl
curl_close($ch); // close the curl