Невозможно продолжить через OAuth2.0 - PullRequest
2 голосов
/ 24 марта 2020

Я сгенерировал токены и код и все, и я могу войти в систему и авторизовать пользователя, но каким-то образом я получаю ошибку. Обнаружены две ошибки.

Первая

(
    [error] => invalid_grant
    [error_description] => Authorization code doesn't exist or is invalid for the client
)

Иногда код авторизации не генерируется, поэтому я получаю ошибку выше. И иногда, когда я могу сгенерировать auth_code, я получаю сообщение об ошибке ниже

{"error":"invalid_token","error_description":"The access token provided is invalid"} 

. Я являюсь разработчиком сайта abcd.com, и теперь у меня есть платформа, на которой мне нужно разработать свой abcd.com для этой платформы. , Для реализации входа в систему я должен использовать OAuth2.0, и это требование платформы. Я прочитал много документов на OAuth2.0 и собрал приложение. Я использую codeigniter, хотя.

сервер. php

$dsn      = 'mysql:dbname=my_oauth2_db;host=localhost';
$username = 'root';
$password = '';

// error reporting (this is a demo, after all!)
ini_set('display_errors',1);error_reporting(E_ALL);

// Autoloading (composer is preferred, but for this example let's just do this)
require_once('oauth2-server-php/src/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();

// $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));

// Pass a storage object or array of storage objects to the OAuth2 server class
$server = new OAuth2\Server($storage);

// Add the "Client Credentials" grant type (it is the simplest of the grant types)
$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));

// Add the "Authorization Code" grant type (this is where the oauth magic happens)
$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));

$scope = new OAuth2\Scope(array(
  'supported_scopes' => array('email')
));
$server->setScopeUtil($scope);

Вот мое разрешение. php

require_once __DIR__.'/server.php';
$request = OAuth2\Request::createFromGlobals();

$client_id      = $request->query['client_id'];
$response = new OAuth2\Response();

if (!$server->validateAuthorizeRequest($request, $response)) {
    $response->send();
    die;
}
if (empty($_POST)) {
  exit('<form method="post">
                  <label>Do You Authorize '.$client_id.'?</label><br />
                  <input class="yes_authorize" type="submit" name="authorized" value="Yes">
                  <input class="no_authorize" type="submit" name="authorized" value="No">
                </form>');
}

$is_authorized = ($_POST['authorized'] === 'Yes');
$server->handleAuthorizeRequest($request, $response, $is_authorized);
if ($is_authorized) {

  $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
  $client_secret        = $_GET['state'];
  $token_value          = shell_exec("curl -u CLIENT_ID:CLIENT_SECRET https://abcd.com/api/token.php -d 'grant_type=authorization_code&code=$code'");

  $token        = json_decode($token_value);
  $access_token = $token->access_token;
  $expires_in   = $token->expires_in;
  $state        = $_GET['state'];

  $resource_result = shell_exec("curl https://abcd.com/api/resource.php -d 'access_token=$code'");

  $redirect_url = $_GET['redirecturi']."?code=$access_token&state=".$_GET['state'];
  exit(header("location: $redirect_url"));
}
$response->send();

ресурс. php

require_once __DIR__.'/server.php';
if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
    $server->getResponse()->send();
    die;
}
echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));

токен. php

require_once __DIR__.'/server.php';

$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();

Если вы видите авторизацию. php, после генерации access_token через токен. php, если я передаю это ресурсу. php, я получаю вторую ошибку. И я передал auth_code, а также access_token, как URL-адрес перенаправления, но мне не удается дозвониться.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...