web-dev-qa-db-fra.com

Créer une nouvelle publication à partir d'une application hybride pour mobile dans WordPress à l'aide du plugin JSON API

Je développe donc une application hybride utilisant cordova et jquery mobile. Je dois me connecter à un site de blog wordpress et créer un nouveau message dans mon application hybride. J'utilise le plugin JSON Api ( https://wordpress.org/plugins/json-api/ ) pour exécuter le message AJAX. Le problème est quand j'essaie de créer un nouveau poste en utilisant le create_post method, j'obtiens l'erreur suivante:

POST _ http // some_localhost_ip/wordpress/api/create_post /? 403 (interdit)

J'ai également utilisé le plug-in utilisateur JSON Api ( https://wordpress.org/plugins/json-api-user/ ) pour l'authentification de l'utilisateur, là où j'utilise la méthode generate_auth_cookie.

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;
    }
});
1
Kaushik Rajbongshi

Eh bien, j’ai abandonné JSON Api pour utiliser maintenant WP Rest API V2. Aussi, un léger changement avec le plugin d'authentification de base que j'avais utilisé avant " WP Auth de base ". C'est défectueux. Essayez d’utiliser le plugin https://github.com/WP-API/Basic-Auth .

J'ai changé mon appel ajax comme ci-dessous:

$.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;
    }
});

Cependant, cette méthode del'authentification de base ne concerne que l'environnement de développement. Je suppose que je dois implémenter l'authentification plus complexe oAuth plus tard: /

0
Kaushik Rajbongshi

vous pouvez utiliser le plugin ci-dessous pour l’authentification, https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

OU vous devez implémenter l’authentification par les méthodes ci-dessous, https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

Lorsque vous envoyez une demande avec un nom d'utilisateur et un mot de passe, vous pouvez obtenir un jeton en réponse. Ensuite, vous devez envoyer ce jeton avec chaque demande avec un en-tête comme ci-dessous pour les besoins de l'authentification,

syntaxe: Autorisation: Jeton <espace>

Exemple: Autorisation: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJINiJ9.eyJpiOiJodHRwOlwvXC9hcHBzLm9wZW50ZXN0ZHJpdmUuY29tOjgwODBcL21hZ25pZmljZW50IiwiF0IjoxNDMjk1LCJuYmYiOjE0OTgxOTYyOTUsImV4cCI6MTQ5ODIwMzQ5NSwiZGF0YSI6eyJ1c2VyIjp7ImliMSJ9fX0.ngBJaXmtKAaBULSUtQZ7eHhqB8YSPjeHuI  enter image description here 

0
Gnanasekaran