1

So i am developing a hybrid app using cordova and jquery mobile. I need to login to a wordpress blog site and create a new post in my hybrid app. I am using JSON Api plugin(https://wordpress.org/plugins/json-api/) to perform AJAX post. The issue is when i try to create a new post using the create_post method,i get the following error:

POST http//some_localhost_ip/wordpress/api/create_post/? 403(Forbidden)

I have also used JSON Api user plugin (https://wordpress.org/plugins/json-api-user/) for user authentication where in i am using the generate_auth_cookie method.

authentication-controller.js

$.ajax({
    url: SERVER_URL + "/api/get_nonce/?controller=user&method=generate_auth_cookie",
    type: "POST",
    headers: {
        'Access-Control-Allow-Headers': 'Content-Type, Accept',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
    },
    crossDomain: true,
    cache: true,
    success: function(result) {
        if (result.status == "ok") {
            var url = SERVER_URL + "/api/user/generate_auth_cookie/?"
            var dataString = {};
            dataString["nonce"] = result.nonce;
            dataString["username"] = username;
            dataString["password"] = password;
            if (!checkBox.is(':checked')) {
                dataString["seconds"] = SESSION_TIMEOUT;
            }
            dataString["insecure"] = "cool"; // remove this if SSL certificate is installed and the url is HTTPS
            $.ajax({
                url: url,
                type: "POST",
                headers: {
                    'Access-Control-Allow-Headers': 'Content-Type, Accept',
                    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
                },
                data: dataString,
                crossDomain: true,
                cache: false,
                success: function(result) {
                    if (result.status == "ok") {
                        window.localStorage.setItem("USERDATA", JSON.stringify(result.user));
                        window.localStorage.setItem("USERCOOKIE", result.cookie);
                        console
                        switch (result.user.role[0]) {
                            case "subscriber":
                                $.mobile.navigate("#page-subscriber-allposts");
                                break;
                            case "author":
                                $.mobile.navigate("#page-author-allposts");
                                break;
                            case "editor":
                                $.mobile.navigate("#page-editor-allposts");
                                break;
                            default:
                                $.mobile.navigate("#page-contributor-allposts");
                                break;
                        }
                    } else {
                        navigator.notification.alert(result.error, function doNothing() {}, "ERROR!", "OK");
                    }
                    return;
                },
                error: function(error) {
                    navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
                    return;
                }
            });
        } else {
            navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
            return;
        }
    },
    error: function(error) {
        navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
        return;
    }
});

workflow-controller.js

var url = SERVER_URL;
if (null != postId && typeof postId != "undefined") {
    url += "/api/get_nonce/?controller=posts&method=update_post";
} else {
    url += "/api/get_nonce/?controller=posts&method=create_post";
}
$.ajax({
    url: url,
    type: "POST",
    headers: {
        'Access-Control-Allow-Headers': 'Content-Type, Accept',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
    },
    crossDomain: true,
    cache: false,
    success: function(result) {
        alert(JSON.stringify(result));
        if (result.status == "ok") {
            var dataString = {};
            if (null != postId && typeof postId != "undefined") {
                url = SERVER_URL + "/api/update_post/?";
            } else {
                url = SERVER_URL + "/api/create_post/?";
                dataString["post_id"] = postId;
            }
            dataString["nonce"] = result.nonce;
            dataString["cookie"] = window.localStorage.getItem("USERCOOKIE");
            dataString["author"] = author;
            dataString["title"] = title;
            dataString["content"] = news;
            $.ajax({
                url: url,
                type: "POST",
                headers: {
                    'Access-Control-Allow-Headers': 'Content-Type, Accept',
                    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
                },
                data: dataString,
                crossDomain: true,
                cache: false,
                success: function(result) {
                    alert(JSON.stringify(result));
                    if (result.status == "ok") {
                        navigator.notification.alert("Your post was successfully submitted and is pending for review", function doNothing() {}, "Hurray!!", "Ok");
                        $.mobile.navigate("#page-author-allposts");
                        return;
                    }else {
                         navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
                         return;
                     }
                },
                error: function(error) {
                    navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
                    return;
                }
            });
        }else {
             navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
             return;
         }
    },
    error: function(error) {
        navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
        return;
    }
});
0

you can use below plugin for authentication, https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

OR you need to implement auth by below methods, https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

When you send request with username and password, you can get token as a response. Then you need to send this token with each request with header like below for the Authentication purpose,

syntax : Authorization : Bearer< space >token

Example: Authorization : Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJINiJ9.eyJpiOiJodHRwOlwvXC9hcHBzLm9wZW50ZXN0ZHJpdmUuY29tOjgwODBcL21hZ25pZmljZW50IiwiF0IjoxNDMjk1LCJuYmYiOjE0OTgxOTYyOTUsImV4cCI6MTQ5ODIwMzQ5NSwiZGF0YSI6eyJ1c2VyIjp7ImliMSJ9fX0.ngBJaXmtKAaBULSUtQZ7eHhqB8YSPjeHuI enter image description here

  • So u are saying the auth method I used should be replaced by JWT? But it supports WP REST API v 2. If i use this api, should the auth token from response be passed to the posts query demo.wp-api.org/wp-json/wp/v2/posts/<id> ? – Kaushik Rajbongshi Jun 20 '17 at 10:58
  • Your wish auth method using, why I suggest this means its have a plugin. its supports api v2 but if you using WP 4.7+ means you don't need WP REST API plugin, because 4.7 inbuilt REST. After implement JWT you send request username and password to WP site it will return token then you need to send this token in header with each request. – Gnanasekaran Jun 20 '17 at 12:10
  • Tried using JWT authentication, but it is still giving me 403 forbidden error. I am sending the token in header like this: headers: { 'Authorization': "JWT "+window.localStorage.getItem("USERCOOKIE"), "Content-Type": "text/plain; charset=utf-8" }, – Kaushik Rajbongshi Jun 21 '17 at 13:52
  • I think you perfectly wrongly sent. refer edited answer – Gnanasekaran Jun 23 '17 at 5:39
  • Refer to an answer i have posted – Kaushik Rajbongshi Jun 23 '17 at 11:50
0

Well, i gave up on JSON Api and now using WP Rest API V2. Also, a slight change with the basic auth plugin i used before "WP Basic Auth". Its faulty. Try using the plugin https://github.com/WP-API/Basic-Auth.

I changed my ajax call as below:

$.ajax({
    url: SERVER_URL + "/wp-json/wp/v2/posts",
    type: "POST",
    headers: {
        'Access-Control-Allow-Headers': 'Content-Type, Accept',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, DELETE',
        'Authorization': 'Basic ' + btoa(username + ":" + password)
    },
    data: dataString,
    crossDomain: true,
    cache: false,
    beforeSend: function() {
        SpinnerPlugin.activityStart("Please wait...", {dimBackground: true});
    },
    complete: function() {
        SpinnerPlugin.activityStop();
    },
    success: function(result) {
       navigator.notification.alert(successMsg, function doNothing() {}, "Success!!", "Ok");
       $.mobile.navigate("#page-author-allposts");
       return;
    },
    error: function(error) {
        console.log(error);
        navigator.notification.alert(errMsg, function doNothing() {}, "Error", "OK");
        return;
    }
});

However, this method of Basic Authenticating is only for development environment. I guess i need to implement the more complex oAuth authentication later on :/

  • change method as a GET not POST, POST used for create post – Gnanasekaran Jun 23 '17 at 12:00
  • you used username is not a admin role ? I think so only response comes like this "you are not allowed to create posts as this user." – Gnanasekaran Jun 23 '17 at 12:01
  • no not an admin user. Its an author, and i am loading posts that are created by that author. I am trying to read the post, not create. even in GET its the same response – Kaushik Rajbongshi Jun 24 '17 at 12:53
  • check with admin credentials – Gnanasekaran Jun 26 '17 at 9:55
  • Sorry, that's not the answer i am looking for.. – Kaushik Rajbongshi Jun 27 '17 at 5:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.