У меня есть логин сервера на мой сайт. Я использую для API Restler 3 с OAuth2.
Server.php:
<?php
namespace Auth;
use Luracast\Restler\iAuthenticate;
use OAuth2\GrantType\UserCredentials;
use OAuth2\Storage\Pdo;
use OAuth2\Server as OAuth2Server;
use OAuth2\GrantType\AuthorizationCode;
use OAuth2\GrantType\ClientCredentials;
use OAuth2\Request;
use OAuth2\Response;
/**
* Class Server
*
* @package OAuth2
*
*/
class Server implements iAuthenticate
{
private $host = DB_HOST;
private $dbName = DB_NAME;
private $user = DB_LOGIN;
private $pass = DB_PASS;
/**
* @var OAuth2Server
*/
protected static $server;
/**
* @var Pdo
*/
protected static $storage;
/**
* @var Request
*/
protected static $request;
public function __construct()
{
$dns = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8";
static::$storage = new PDO(
array('dsn' => $dns, 'username' => $this->user, 'password' => $this->pass)
);
$grantTypes = array(
'authorization_code' => new AuthorizationCode(static::$storage),
'user_credentials' => new UserCredentials(static::$storage),
);
static::$request = Request::createFromGlobals();
static::$server = new OAuth2Server(
static::$storage,
array('enforce_state' => true, 'allow_implicit' => true),
$grantTypes
);
$grantType = new ClientCredentials(static::$storage);
static::$server->addGrantType($grantType);
}
/**
* Stage 2: User response is captured here
*
* Success or failure is communicated back to the Client using the redirect
* url provided by the client
*
* On success authorization code is sent along
*
*
* @param bool $authorize
*
* @return \OAuth2\Response
*
* @format JsonFormat,UploadFormat
*/
public function postAuthorize($authorize = false)
{
static::$server->handleAuthorizeRequest(
static::$request,
new Response(),
(bool)$authorize
)->send();
exit;
}
/**
* Stage 3: Client directly calls this api to exchange access token
*
* It can then use this access token to make calls to protected api
*
* @format JsonFormat,UploadFormat
* @access public
* @url POST apiMobile/grand
* @url GET apiMobile/rer
*/
public function postGrant()
{
static::$server->handleTokenRequest(static::$request)->send();
exit;
}
/**
* Access verification method.
*
* API access will be denied when this method returns false
*
* @return boolean true when api access is allowed; false otherwise
*/
public function __isAllowed()
{
$token = static::$server->getAccessTokenData(Request::createFromGlobals());
global $idClient;
$idClient = $token['client_id'];
return self::$server->verifyResourceRequest(static::$request);
}
public function __getWWWAuthenticateString()
{
return 'auth string';
}
}
?>
И init.php:
<?php
use Luracast\Restler\Restler;
class ApiMode
{
private $class = '';
private $function = '';
public function __construct($controller = DEFAULT_CONTROLLER, $function = DEFAULT_FUNCTION)
{
$this->class = $controller;
$this->function = $function;
$controllerClass = ucfirst($this->class).CONTROLLER_TERMINAL;
$controllerPatch = CONTROLLER_DIR.'/'.$controllerClass.'.php';
require_once $controllerPatch;
require_once EXTERN_DIR.'/OAuth2/Autoloader.php';
OAuth2\Autoloader::register();
require_once EXTERN_DIR.'/vendor/restler.php';
require_once CLASS_DIR.'/Server.php';$r = new Restler();$r->addAuthenticationClass('Auth\\Server', '');
$r->setSupportedFormats('JsonFormat', 'XmlFormat');//,
$r->addAPIClass($controllerClass,'');
$r->setOverridingFormats('JsonFormat');
$r->setOverridingFormats('UploadFormat');
$r->handle();
}
}
?>
Я использую только Stage 3 — postGrand для получения токена доступа.
Из веб-браузера на Http: //mypage/apiMobile/rer.json (GET для тестирования из моего веб-браузера, если GET работает, POST работает хорошо) get:
локальный сервер Windows (это нормально):
{"error":"invalid_request","error_description":"The request method must be POST when requesting an access token","error_uri":"http:\/\/tools.ietf.org\/html\/rfc6749#section-3.2"}
веб-сервер (использовать https) Linux PHP 5.5.21 (ошибка):
{
"error": {
"code": 404,
"message": "Not Found"},
"debug": {
"source": "Routes.php:438 at route stage",
"stages": {
"success": [
"get"],
"failure": [
"route",
"negotiate",
"message"]
}
}
}
На веб-сервере и локальной работе все из API (адрес: mypage / apiMobile / myApi.json из контроллера):
$r->addAPIClass($controllerClass,'');
Основная проблема с доступом к OAuth2 (мне нужен доступ из Http: //mypage/apiMobile/rer.json). Любая идея или учебник?
Благодарю.
Задача ещё не решена.
Других решений пока нет …