You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java对接WordPress REST API:登录后无法保持用户认证状态?

问题

我在Android的LoginActivity中实现了WordPress后端登录功能,服务器返回200状态码表示登录成功,但跳转到DashboardActivity尝试创建文章时,服务器返回:

"Sorry, you are not allowed to create posts as this user."
我使用的是管理员账号,请问如何解决?


LoginActivity(登录成功代码)

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(创建文章失败代码)

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");
        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;
    }
}

解决方案

问题核心是创建文章的请求没有携带有效的认证信息,WordPress REST API无法识别当前请求的用户身份,即使你之前登录过。

步骤1:保存登录后的认证凭证

你的自定义登录插件在返回200响应时,应该会附带认证令牌(比如JWT Token)或会话Cookie。需要解析响应内容,将凭证保存到本地(比如SharedPreferences):

修改LoginActivity的登录成功逻辑:

if (responseCode == 200) {
    // 解析响应获取认证令牌(假设接口返回格式为 {"token": "xxx"})
    JSONObject resJson = new JSONObject(resStr);
    String authToken = resJson.getString("token");
    
    // 保存令牌到SharedPreferences
    SharedPreferences sp = getSharedPreferences("WP_AUTH", MODE_PRIVATE);
    sp.edit().putString("AUTH_TOKEN", authToken).apply();

    Log.i("We're logged in!", String.valueOf(responseCode));
    Intent i = new Intent(LoginActivity.this, DashboardActivity.class);
    startActivity(i);
}

步骤2:创建文章时携带认证信息

在DashboardActivity的请求中,添加认证头(以JWT为例),让WordPress识别用户身份:

修改DashboardActivity的请求构建代码:

// 从SharedPreferences读取保存的令牌
SharedPreferences sp = getSharedPreferences("WP_AUTH", MODE_PRIVATE);
String authToken = sp.getString("AUTH_TOKEN", "");

Request request = new Request.Builder()
        .url("http://myurl.com/wp-json/wp/v2/posts")
        // 添加JWT认证头
        .addHeader("Authorization", "Bearer " + authToken)
        .post(body)
        .build();

额外检查项

  1. 确认自定义登录插件生成的认证令牌具有管理员权限,且令牌未过期。
  2. 检查WordPress后台的REST API设置,确保管理员角色拥有创建文章的权限(默认管理员是有的,但可能被插件修改)。
  3. 如果使用Cookie认证,需要在OkHttpClient中保存并复用登录时的CookieJar,确保请求携带会话Cookie。

内容的提问来源于stack exchange,提问作者Brittany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:45:39