Search code examples
rubyoauthwordpressnet-http

Authentication Issue with WP-API and Net::Http


I am new to Wordpress. I want to access WP-API to create a post using REST API. I am unable to perform POST, PUT and Delete request. Though I can retrieve data only. I wrote a ruby script for this. Below is my code snippet.

require 'net/http'
require 'net/http/oauth'
require 'json'

class CollectScript
  def initialize
    uri = URI.parse('http://vagrant.local/wp-json/wp/v2/posts')
    http = Net::HTTP.new(uri.host, uri.port)
    req = Net::HTTP::Post.new(uri.request_uri)
    req.basic_auth("admin", "password")
    res = http.request(req)     
    puts res.body
  end
end
CollectScript.new

While running the above code I am getting following error:

{"status":"error","error":"You need to login with a user capable of creating posts."}

Using the same code with GET request I am able to get the posts JSON. But for HTTP POST request I need to pass authentication. I tried with basic authentication and Oauth too. But same result.

Please can anyone help me to figure out the issue with authentication.


Solution

  • I simply install this basic_auth plugin in my Wordpress site.

    • First, I download the zip file from this link
    • Now extract it to /content/plugins folder in your project directory
    • Activate this plugin from your wp-admin interface.
    • Now I use the following code snippet for authentication

      uri = URI.parse("http://vagrant.local/wp-json/wp/v2/posts")
      http = Net::HTTP.new(uri.host, uri.port)
      req = Net::HTTP::Post.new(uri.request_uri)
      req.basic_auth("admin", "password")
      req.set_form_data({title: "Another 11new post", status: "publish", content_raw: "this is the content of the post", excerpt_raw: "Excerpt", post_media: ['/uploads/rails.png']})
      res = http.request(req)   
      puts res.body
      

    Now It successfully works.