oauth2 api_WP API和OAuth-在没有WordPress的情况下使用WordPress

oauth2 api

In this tutorial, we’ll learn how to install and use WP-API with OAuth – a WordPress plugin which uses REST-like API endpoints to allow reading of WP content to unauthenticated users, and writing of WP content to users who authenticate via OAuth (or via Cookies for themes and plugins).

在本教程中,我们将学习如何通过OAuth安装和使用WP-API –一个WordPress插件,该插件使用类似REST的API端点,以允许未经身份验证的用户读取WP内容,以及向通过OAuth进行身份验证的用户写入WP内容(或通过Cookies来获取主题和插件)。

WordPress Logo

Using the plugin isn’t very straightforward, and the prerequisite list is quite long, so this post was written to make it simple and relatively approachable (as long as you’re in control of your own server).

使用插件不是很简单,前提条件列表很长,因此写这篇文章是为了使其简单且相对容易(只要您控制自己的服务器)。

The tutorial assumes basic familiarity with the terminal, and with Vagrant for ease of development.

本教程假定您对终端和Vagrant具有基本的了解,以便于开发。

正在安装 (Installing)

As usual, we’ll be using SitePoint’s trusty Homestead Improved instance to get a fresh environment up and running:

和往常一样,我们将使用SitePoint值得信赖的Homestead Improvement实例来启动并运行一个新的环境:

git clone https://github.com/swader/homestead_improved hi_wp_github
cd hi_wp_github
sed -i '' "s@map\: \.@map\: $PWD@g" Homestead.yaml

That last line is a shortcut that makes the current folder of the host machine shared into the VM’s Code folder. I also changed the sites block to:

最后一行是使主机的当前文件夹共享到VM的Code文件夹中的快捷方式。 我也将site块更改为:

sites:
    - map: test.app
      to: /home/vagrant/Code/wptest

Remember to have test.app (or the URL you choose) in your /etc/hosts file, as per instructions.

请记住,按照说明/etc/hosts文件中包含test.app (或您选择的URL)。

Next, we get a new instance of WP up and running. Since Homestead has MySQL pre-installed, this is a piece of cake.

接下来,我们将启动并运行WP的新实例。 由于Homestead已预安装MySQL,因此这是小菜一碟。

cd ~/Code
wget https://wordpress.org/latest.tar.gz
tar -xvzf latest.tar.gz
mv wordpress wptest
cd wptest
cp wp-config-sample.php wp-config.php

After we update wp-config.php accordingly and set up our keys and database credentials, the WP instance is ready and can be finalized by running it in the browser.

在我们相应地更新wp-config.php并设置了密钥和数据库凭据之后,WP实例已准备就绪,可以通过在浏览器中运行它来完成该实例。

WP-API (WP-API)

Despite the flak it’s taken over the years (a large part of it fired from my own Dual Flak Cannons), WP really is trying to get with the times while still accommodating their old, technically inept userbase.

尽管经历了多年的打击(其中很大一部分是由我自己的Dual Flak Cannons发射的),但是WP确实在设法与时俱进,同时仍然适应了技术上无能为力的旧用户群。

One such effort is the WP-API, a REST-like set of endpoints built into WP as a plugin so that the internals of a WordPress installation can become accessible to the outside. For example, getting your posts in JSON format is as simple as pinging /wp-json/posts.

其中一项工作就是WP-API ,这是一套类似REST的端点,作为WP内置于WP中,以便外部可以访问WordPress安装的内部。 例如,以JSON格式获取帖子就像ping /wp-json/posts一样简单。

It can be easily installed via the default plugin manager – the stable version is 1.2.* at the time of this writing – so let’s do that.

可以通过默认的插件管理器轻松地安装它-撰写本文时,稳定版本为1.2。*-因此,让我们这样做。

Installing the wp-rest-api plugin

If we test immediately after installation, the URL /wp-json/posts should produce a JSON array of the initial “Hello World” post. However, the actual submission process (updating and posting) isn’t as simple.

如果我们在安装后立即进行测试,则URL /wp-json/posts应该会生成初始“ Hello World”帖子的JSON数组。 但是,实际的提交过程(更新和发布)并不那么简单。

OAuth –服务器 (OAuth – Server)

Unfortunately, as with all things WP, even their attempts to be modern are already out of date.

不幸的是,与WP一样,即使他们尝试现代化,也已经过时了。

As such, they use OAuth1 rather than OAuth2 for authentication. For that, we’ll need the OAuth1 plugin installed. For that, though, we need the wp-cli upgrade, a way to use WP commands from the terminal:

因此,他们使用OAuth1而不是OAuth2进行身份验证。 为此,我们需要安装OAuth1插件。 为此 ,虽然,我们需要的wp-cli升级,使用从终端WP命令的方式:

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

Then, we grab the OAuth plugin:

然后,我们获取OAuth插件:

cd ~/Code/wptest
git clone https://github.com/WP-API/OAuth1 wp-content/plugins/oauth-server

Activate the plugin (which should now appear in the Plugins list) and back in the terminal run:

激活插件(现在应该显示在“插件”列表中),然后在终端运行中返回:

wp oauth1 add

This should produce a key / secret combination that can be used for OAuth authentication:

这应该产生可用于OAuth身份验证的密钥/机密组合:

ID: 4
Key: xOp1fGMgouBl
Secret: Sk7YcM48qsmcDPp2NSmna3kMEfTtDNfxpy43xjWp1mSP7ytw

Aside from being out of date with their protocol approach, there’s also the problem of us having to use 3-legged OAuth rather than something simpler, UI-less like 2-legged OAuth flow. For differences, read this extensive guide. Hopefully, that’ll improve later.

除了过时地使用其协议方法外,还有一个问题,就是我们必须使用三足式OAuth,而不是像两足式OAuth流那样使用更简单,没有UI的东西。 如有差异,请阅读本详尽指南 。 希望以后会有所改善。

The good news, though, is that if you’re the owner of the WP site and you’re enabling OAuth API access for others – you’re done! It’s up to them to develop a client, and that’s what we’ll do next.

不过,好消息是,如果您是WP网站的所有者 ,并且正在为其他人启用OAuth API访问权限,那么您就完成了! 开发客户取决于他们,这就是我们接下来要做的。

OAuth –客户端 (OAuth – Client)

To test submissions into WP via WP-API, we need an “app” to serve as the “submitter”. For that, we make a new project in another folder in the virtual machine – perfect for testing. First, we edit the virtual machine’s Homestead.yaml file to include a new site:

要通过WP-API测试提交到WP的提交,我们需要一个“应用程序”作为“提交者”。 为此,我们在虚拟机的另一个文件夹中创建了一个新项目,非常适合测试。 首先,我们编辑虚拟机的Homestead.yaml文件以包括一个新站点:

sites:
    - map: test.app
      to: /home/vagrant/Code/wptest
    - map: test2.app
      to: /home/vagrant/Code/submitter

Then, we exit the VM with exit and re-provision with vagrant provision and then re-renter the VM with vagrant ssh. Now that our submitter virtual host is defined, let’s add a simple index.php file into it, and a (for now) empty callback.php file.

然后,我们与退出VM exit并重新提供与vagrant provision ,然后用重新R输入VM vagrant ssh 。 现在已经定义了submitter虚拟主机,让我们submitter添加一个简单的index.php文件和一个(现在)空的callback.php文件。

mkdir ~/Code/submitter
touch ~/Code/submitter/index.php
touch ~/Code/submitter/callback.php
touch ~/Code/submitter/credentials.php
cd ~/Code/submitter

The credentials file should hold the keys we got from the WP app:

凭证文件应包含我们从WP应用获得的密钥:

// credentials.php
<?php

return [
    'consumer_key' => 'xOp1fGMgouBl',
    'consumer_secret' => 'Sk7YcM48qsmcDPp2NSmna3kMEfTtDNfxpy43xjWp1mSP7ytw'
];

We’ll also need some packages installed:

我们还需要安装一些软件包:

composer require --dev symfony/var-dumper
composer require guzzlehttp/guzzle:~5

VarDumper is there to help us debug, and Guzzle 5 is there to help us issue requests at the WP-API. We could use a generic OAuth client, but why not use Guzzle’s?

VarDumper可以帮助我们进行调试,而Guzzle 5可以帮助我们在WP-API上发出请求。 我们可以使用通用的OAuth客户端,但是为什么不使用Guzzle的呢?

composer require guzzlehttp/oauth-subscriber

Note that the submitter we’ll be building below is just a demo script, and should only be used as inspiration for implementing OAuth+WP-API in your own application, not as a full application demo.

请注意,我们将在下面构建的提交者只是一个演示脚本,仅应作为在您自己的应用程序中实现OAuth + WP-API的灵感,而不是作为完整的应用程序演示。

One more thing – by default, WordPress blocks login redirections to external sites (those differing in domain) so a new filter needs to be added which will allow this. Back in the WP app’s sources, open default-filters.php and add the following somewhere into the file:

还有一件事–默认情况下,WordPress阻止登录重定向到外部站点(这些站点的域不同),因此需要添加一个新的过滤器以允许这样做。 返回WP应用程序的源代码,打开default-filters.php并将以下内容添加到文件中:

add_filter( 'allowed_redirect_hosts' , 'my_allowed_redirect_hosts' , 10 );
function my_allowed_redirect_hosts($content){
    $content[] = 'test2.app';
    return $content;
}

Naturally, replace test2.app with your own URL if you used a different one.

当然,如果您使用其他URL,请用您自己的URL替换test2.app

身份验证–腿1 (Authentication – Leg 1)

Authenticating with WP API over OAuth is something that’s completely missing from the docs, but that’s because OAuth authentication is something that’s quite specific and almost identical across projects. That doesn’t mean it’s simple, though. We’ll mostly be following the procedure from this post, in one way or another.

在OAuth上使用WP API进行身份验证是文档中完全没有的,但这是因为OAuth身份验证是非常具体的,并且在整个项目中几乎相同 。 不过,这并不意味着它很简单。 我们将主要从以下的步骤这篇文章 ,以这种或那种方式。

Give the index.php file the following contents:

index.php文件提供以下内容:

<?php

require_once 'vendor/autoload.php';

session_start();

use GuzzleHttp\Client;
use GuzzleHttp\Subscriber\Oauth\Oauth1;

$client = new Client([
    'defaults' => ['auth' => 'oauth']
]);

$oauth = new Oauth1(include 'credentials.php');

$client->getEmitter()->attach($oauth);
$callback = 'http://test2.app/callback.php';

$req = $client->createRequest("POST", 'http://test.app/oauth1/request',
    ['body' => ['oauth_callback' => $callback]]);

try {

    $res = $client->send($req);
    parse_str($res->getBody());

    $_SESSION['oauth_token'] = $oauth_token;
    $_SESSION['oauth_token_secret'] = $oauth_token_secret;

    header("Location: http://test.app/oauth1/authorize?oauth_token={$oauth_token}&oauth_callback=".$callback);

} catch (\Exception $e) {
    dump($e);
}

First, we define a new Guzzle client and set its default auth mode as Oauth. Then, we set up a new OAuth1 client instance and give it the key and secret we got before by running wp oauth1 add. We use this instance as an emitter and create a POST request from it (also defining a callback – the URL to which WP is supposed to redirect us once we authorize it), which is then sent to our WP app.

首先,我们定义一个新的Guzzle客户端,并将其默认身份验证模式设置为Oauth。 然后,我们设置一个新的OAuth1客户端实例,并通过运行wp oauth1 add之前获得的密钥和秘密。 我们使用此实例作为发射器,并从中创建POST请求(还定义了回调-授权后WP应该将我们重定向到的URL),然后将其发送到WP应用程序。

In the try/catch block, we turn the response into two strings: $oauth_token and $oauth_token_secret, both of which we need to continue the auth process. We save them into the session, and go on to step 2: the callback.php file.

在try / catch块中,我们将响应转换为两个字符串: $oauth_token$oauth_token_secret ,这两个字符串都需要我们继续进行身份验证过程。 我们将它们保存到会话中,然后继续执行步骤2: callback.php文件。

身份验证–第2条 (Authentication – Leg 2)

For the second leg of the 3-legged OAuth flow, we need to build the callback.php file.

对于三足OAuth流的第二 ,我们需要构建callback.php文件。

When we log into WP and Authorize our submitter app, WP sends us back to the callback URL we provided. It’ll also send along some additional params: oauth_token, oauth_verifier and wp_scope.

当我们登录WP并授权提交者应用程序时,WP将我们发送回我们提供的回调URL。 它还将发送一些其他参数: oauth_tokenoauth_verifierwp_scope

We use the verifier and the oauth_token to send a request to the /access endpoint and get an access token (the secret) which will finally let us do operations on the database.

我们使用验证程序和oauth_token将请求发送到/access端点,并获得访问令牌( secret ),该令牌最终将使我们能够对数据库进行操作。

<?php

require_once 'vendor/autoload.php';

session_start();

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Subscriber\Oauth\Oauth1;

$authToken = $_GET['oauth_token'];
$authVerifier = $_GET['oauth_verifier'];

$client = new Client(['defaults' => ['auth' => 'oauth']]);

$oauth = new Oauth1(
    array_merge(include 'credentials.php',
        ['token' => $_SESSION['oauth_token']])
);

$client->getEmitter()->attach($oauth);

if ($authToken == $_SESSION['oauth_token']) {
    $req = $client->createRequest("POST", 'http://test.app/oauth1/access',
        ['body' => ['oauth_verifier' => $authVerifier]]);

    try {
        $res = $client->send($req);

        $params = (string)$res->getBody();

        parse_str($params);

        $_SESSION['oauth_token'] = $oauth_token;
        $_SESSION['oauth_token_secret'] = $oauth_token_secret;

        header("Location: makepost.php");
    } catch (ClientException $e) {
        dump((string)$e->getResponse()->getBody());
    } catch (\Exception $e) {
        dump($e);
    }
}

身份验证–第3条 (Authentication – Leg 3)

Finally, let’s create a file makepost.php which we’ll use to create a sample post in our WP app – if that goes through, it means everything is working just fine.

最后,让我们创建一个文件makepost.php ,将其用于在WP应用程序中创建示例帖子–如果成功,则表示一切正常。

<?php

require_once 'vendor/autoload.php';

session_start();

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Subscriber\Oauth\Oauth1;

$client = new Client([
    'defaults' => ['auth' => 'oauth']
]);

$array = array_merge(include 'credentials.php', [
    'token' => $_SESSION['oauth_token'],
    'token_secret' => $_SESSION['oauth_token_secret']
]);

$oauth = new Oauth1($array);

$client->getEmitter()->attach($oauth);

$post = [
    'title' => 'From outside!',
    'content' => 'This post was submitted via the API!!!',
    'status' => 'publish'
];

$req = $client->createRequest("POST", 'http://test.app/wp-json/posts',
    ['json' => $post]);

try {
    $res = $client->send($req);
    dump((string)$res->getBody());
} catch (ClientException $e) {
    dump((string)$e->getResponse()->getBody());
} catch (\Exception $e) {
    dump($e);
}

We’ve got a simple “post” in the form of an array with three fields, and defaulting to “publish” mode so we can immediately see it on the home page of our WP app, without having to go into the editor and publish it manually.

我们以具有三个字段的数组的形式获得了一个简单的“发布”,并且默认为“发布”模式,因此我们可以立即在WP应用程序的主页上看到它,而无需进入编辑器并发布手动。

After execution, the post should be visible on the home screen of our WP app:

执行后,该帖子应在我们的WP应用的主屏幕上可见:

Post has been published

Of course, the three files above (index.php, callback.php, makepost.php) are examples of OAuth use, and should probably be turned into something more reusable and coherent, but for purely testing if the integration works, they’re just fine. Fear not, though – we’ll be upgrading this significantly in an upcoming post.

当然,上面的三个文件( index.phpcallback.phpmakepost.php )是OAuth使用的示例,应该将其转换为更可重用和更连贯的东西,但是为了纯粹测试集成是否有效,它们是正好。 不过请不要担心–我们将在即将发布的帖子中对其进行重大升级。

结论 (Conclusion)

In this tutorial, we installed and activated WP-API and WP-Oauth, in an attempt to make our WP installation accessible to the outside (authenticated) world. As you can see, it’s not exactly straightforward, but hopefully this tutorial helped in getting you up and running.

在本教程中,我们安装并激活了WP-API和WP-Oauth,以使我们的WP安装对外界(已认证)可用。 如您所见,这并不完全简单,但是希望本教程有助于您入门和运行。

Have you had experiences with WP-API yet? Would you like to see more examples? Let us know!

您有使用WP-API的经验吗? 您想查看更多示例吗? 让我们知道!

翻译自: https://www.sitepoint.com/wp-api-and-oauth-using-wordpress-without-wordpress/

oauth2 api

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值