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.


正在安装 (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块更改为:

    - 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.



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.


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.


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:


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:


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文件以包括一个新站点:

    - 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:


// credentials.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.


身份验证–腿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:



require_once 'vendor/autoload.php';


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

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

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

$callback = 'http://test2.app/callback.php';

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

try {

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

    $_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) {

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 ),该令牌最终将使我们能够对数据库进行操作。


require_once 'vendor/autoload.php';


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']])


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();


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

        header("Location: makepost.php");
    } catch (ClientException $e) {
    } catch (\Exception $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应用程序中创建示例帖子–如果成功,则表示一切正常。


require_once 'vendor/autoload.php';


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);


$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);
} catch (ClientException $e) {
} catch (\Exception $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.


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


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
OAuth2的access_token是用于访问受保护的资源时进行身份验证和授权的凭证。通过将access_token附加到请求头或请求参数中,客户端可以向资源服务器发送请求并获得资源的访问权限。access_token通常是使用JWT(JSON Web Token)进行签名的,以确保其安全性和完整性。然而,access_token只提供了身份验证的功能,而没有提供有关用户的其他信息。这就是为什么在OAuth2中还存在idToken的原因。idToken是一个包含用户相关信息的令牌,如用户ID、姓名、电子邮件等。它通常被用于提供身份验证和用户信息的完整性,并且可以通过认证服务器的/token端点进行验证。因此,通过同时使用access_token和idToken,客户端可以获得对资源的访问权限,并获得关于用户的更详细的信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [【笔记】浅谈OAuth2 accessToken和OIDC idToken的理解和使用场景](https://blog.csdn.net/qq_26878363/article/details/115394602)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springsecurity-oauth2令牌 access_token验证](https://blog.csdn.net/clonetx/article/details/125395593)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]


  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助




当前余额3.43前往充值 >
领取后你会自动成为博主和红包主的粉丝 规则
钱包余额 0