Search code examples
javaandroidwordpressrestwordpress-rest-api

Java/Wordpress REST API - Keep user authenticated?


I'm using the below code on my main activity to log the user into my app. The app's backend is Wordpress. The server returns a success message, and the user is authenticated, but as soon as I get to the next screen/activity, and attempt to have the user create a post to wordpress, the server returns the message

"Sorry, you are not allowed to create posts as this user."

Especially odd in this case because the user credentials I'm using to login are the admin user.

Any idea how I can fix this?

LoginActivity (my user logs in successfully):

  private class UserNetwork extends AsyncTask<Void, Void, Void> {
            @Override
            protected Void doInBackground(Void... voids) {
    
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("username", "admin");
                    jsonObject.put("password", "123456");
    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
    
                OkHttpClient client = new OkHttpClient();
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
               
                RequestBody body = RequestBody.create(JSON, jsonObject.toString());
                Request request = new Request.Builder()
                        .url("http://myurl.com/wp-json/wp/v2/custom-plugin/login")
                        .post(body)
                        .build();
    
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    String resStr = response.body().string();
                    Log.i("The response is", String.valueOf(response));
                    int responseCode = response.code();
                    Log.i("Check response code", String.valueOf(responseCode));
    
                    if (responseCode == 200) {
    
    
                        Log.i("We're logged in!", String.valueOf(responseCode));
    
                        Intent i = new Intent(LoginActivity.this, DashboardActivity.class);
                        startActivity(i);
    
    
                }
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
    
                return null;
            }

DashboardActivity (user attempts to create post, and 'Unauthorized' messsage is returned):

 private class UserPosts extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("title", "Our first post");
                jsonObject.put("content", "this is a test");
                jsonObject.put("status", "publish");


            } catch (JSONException e) {
                e.printStackTrace();
            }

            OkHttpClient client = new OkHttpClient();
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            // put your json here
            RequestBody body = RequestBody.create(JSON, jsonObject.toString());
            Request request = new Request.Builder()
                    .url("http://myurl.com/wp-json/wp/v2/posts")
                    .post(body)
                    .build();

            Response response = null;
            try {
                response = client.newCall(request).execute();
                String resStr = response.body().string();
                Log.i("The response is", String.valueOf(response));
                int responseCode = response.code();
                Log.i("Check response code", String.valueOf(responseCode));

                if (responseCode == 200) {


                    Log.i("Creating post!", String.valueOf(responseCode));



                } else {

                    Log.i("Post not created.", String.valueOf(responseCode));

                }

            } catch (IOException e) {
                e.printStackTrace();
            }


            return null;
        }
    }

Solution

  • The problem you're having is caused by HTTP protocol being stateless. That means whenever you perform request, server treats you as a new entity.

    In case of most authenticated requests, the client is responsible for storing the tokens issued by the server during the login, and then passing them to following requests.

    When you are using the browser it is the client and usually is being responsible for handling this state (it ma also be a JavaScript code running in the browser).

    In your code that is your responsibility to store this state. While you're using OkHttp, you could use CookieJar and it would probably work. However in the end using user credentials to authenticate application is not the best idea and using extension that would allow you to specify credentials for an application as @faozi suggested would probably be a better solution.