這些天,一直在忙着搞一個分享Event的平台,其中用到了Wordpress架構網站。花了一整個下午,我才成功用Postman 連接到在localhost MAMP 上的Wordpress ,並建立了第一個tag。
WordPress官方提供的Authentication方法只有cookie authentication,在後端不知道該怎麼弄,所以果斷放棄了這個方法。除了cookie authentication,還可以用plugin進行身份驗證。不過,3個plugin當中,只有一個成功讓我通過驗證,具體錯誤的原因不明⋯⋯
第一種,JSON Web Tokens。我按照着官方說明,在wp-config.php中加入了以下了兩句,訪問了/WP-JSON/JWT-AUTH/V1/TOKEN 成功拿到token。可是在之後的request裡加上token,依然無法通過驗證。
define('JWT_AUTH_SECRET_KEY', 'your-top-secrect-key')
;
define('JWT_AUTH_CORS_ENABLE', true);
第二種, OAuth 1.0a Server。這個plugin沒有具體的方法,我google了幾篇教學,內容都大同小異,詳情可以參考Set Up Postman for WordPress WP REST API。我卡在了最後一步,拿到了oauth token 和oauth token secret卻又是不能通過驗證,一直出現
{
"code": "rest_cannot_create",
"message": "Sorry, you are not allowed to create new terms.",
"data": {
"status": 401
}
第三種,Application Passwords。這個plugin安裝之後,只需要在User頁面新增一個Application password,每一次後端連接到wordpress 就用Basic Auth,填上user id 和 這個application password (不是原來登入的密碼),就能成功驗證。
下一步,我要把後端的資料通通灌到Wordpress⋯⋯
Reference
- 在macOS上建立Wordpress:https://codex.wordpress.org/Installing_WordPress_Locally_on_Your_Mac_With_MAMP
- WordPress authentication:https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/