如何使用Wordpress Rest Api获取当前登录用户?

Sem*_*nko 20 php wordpress

我试图添加自定义请求.

add_action('rest_api_init', function () {
    register_rest_route( 'custom', '/login', array(
        'methods' => 'GET',
        'callback' => function(WP_REST_Request $request) {
            return wp_get_current_user();
        }
    ));
});
Run Code Online (Sandbox Code Playgroud)

但它总是返回ID = 0的用户; 我也试过这个:

add_action('rest_api_init', function () {
    register_rest_route( 'custom', '/login', array(
        'methods' => 'GET',
        'callback' => function(WP_REST_Request $request) {
            return is_user_logged_in();
        }
    ));
});
Run Code Online (Sandbox Code Playgroud)

它总是返回false.但是用户肯定已登录.

我添加了自定义登录

add_action('rest_api_init', function () {
    register_rest_route( 'custom', '/login', array(
        'methods' => 'POST',
        'callback' => function(WP_REST_Request $request) {
            $nonce = wp_create_nonce("wp_rest");
            $user = wp_signon(array('user_login' => $_POST['username'],
                'user_password' => $_POST['password'], "rememberme" => true), false);
            if (is_wp_error($user)) {
                return $user;
            }

            //do_action( 'wp_login', "capad" );
            //$user['isloggedin'] = is_user_logged_in();
            return array('user' => $user,
                'nonce' => $nonce);
        }
    ));
});
Run Code Online (Sandbox Code Playgroud)

我将"X-WP-Nonce"添加为http请求的标头

现在每个请求输出: {"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid","data":{"status":403}}

bir*_*ire 18

身份验证章节,在REST API手册中:

Cookie身份验证是WordPress附带的基本身份验证方法.当您登录仪表板时,这会为您正确设置cookie,因此插件和主题开发人员只需拥有一个已登录的用户.

但是,REST API包含一种名为nonces的技术,可以避免CSRF问题.这可以防止其他站点强制您执行操作,而无需明确打算这样做.这需要对API进行稍微特殊的处理.

对于使用内置Javascript API的开发人员,这将自动为您处理.这是将API用于插件和主题的推荐方法.自定义数据模型可以扩展wp.api.models.Base以确保为任何自定义请求正确发送.

对于制作手动Ajax请求的开发人员,需要在每个请求中传递随机数.API使用动作设置为的nonce wp_rest.然后可以通过_wpnonce数据参数(POST数据或GET请求的查询)或通过X-WP-Nonce标头将这些传递给API .

这是一个GET示例:

https://example.tld/wp-json/wp/v2/users/me?_wpnonce=9467a0bf9c
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下:

https://example.tld/wp-json/custom/login/?_wpnonce=9463a0bf9c
Run Code Online (Sandbox Code Playgroud)

nonce是从哪里创建的

wp_create_nonce( 'wp_rest' );
Run Code Online (Sandbox Code Playgroud)

因此,在测试自定义端点时,您很可能忘记了nonce部分.

希望能帮助到你!

  • 随机数必须与客户端的请求一起出现,而不是在其余服务器的响应中生成。例如,首先尝试使用`/ wp-json / wp / v2 / users / me /`端点,客户端向该端点发送随机数,并使其显示当前用户信息。@SemyonTikhonenko (2认同)
  • "API使用nonce,动作设置为`wp_rest`"是的,我总是改变它,它搞砸了我. (2认同)

sha*_*rif 11

我花了两天时间寻找一种不添加插件的简单方法。

首先在 function.php 中定义您的 api

//enqueue the script which will use the api
function api_callings_scripts() {
    wp_enqueue_script('score-script', get_template_directory_uri() . '/js/ScoreSaving.js', ['jquery'], NULL, TRUE);
    // Pass nonce to JS.
    wp_localize_script('score-script', 'ScoreSettings', [
      'nonce' => wp_create_nonce('wp_rest'),
    ]);
}
add_action( 'wp_enqueue_scripts', 'api_callings_scripts' ); 
Run Code Online (Sandbox Code Playgroud)

然后你的脚本 Ajax 调用云是这样的

jQuery.ajax({
      type: "POST",
      url: "/wp-json/score/update",
      data: {"var1":"value1"},
      beforeSend: function(xhr) {
        xhr.setRequestHeader('X-WP-Nonce', ScoreSettings.nonce);
      },
    success: 
        function( data ) {
          console.log( data );
        }
    });
Run Code Online (Sandbox Code Playgroud)

现在您可以get_current_user_id()在 API 代码中使用。

  • 简单、高效、完美! (2认同)

小智 10

这是另一种方法

$user_id = ""; //<- add this

add_action( 'rest_api_init', 'add_custom_users_api');

function add_custom_users_api(){
    $GLOBALS['user_id'] = get_current_user_id(); //<- add this

    // route url: domain.com/wp-json/mmw/v1/testing
    register_rest_route( 'mmw/v1', 'testing', array(
        'methods' => 'GET',
        'callback' => 'get_custom_users_data',
    ));
}
//Customize the callback to your liking
function get_custom_users_data(){
    return get_user_by( 'id', $GLOBALS['user_id'] ); //<- add this
}
Run Code Online (Sandbox Code Playgroud)


shi*_*hiv 8

1.安装并激活WP REST API 插件的 JWT 身份验证,同时安装 WP REST API 插件
2.现在您可以从移动应用程序或任何其他来源或通过邮递员运行任何 wordpress 默认 api。例如,从您的应用程序或邮递员点击此网址。https://example.com/wp-json/wp/v2/posts
3.通过应用程序或邮递员,当您使用有效详细信息(使用 rest api)登录时,您将获得一个令牌。要登录并获取令牌,请通过邮递员或应用程序运行以下网址 https://example.com/wp-json/jwt-auth/v1/token
4.通过这种方式您将获得如图所示的令牌 邮递员和 jwt 身份验证
现在使用这个令牌来获取登录的用户详细信息,例如
5.在 function.php 中的 make 函数

function checkloggedinuser()
{
$currentuserid_fromjwt = get_current_user_id();
print_r($currentuserid_fromjwt);
exit;
}

 add_action('rest_api_init', function ()
{
  register_rest_route( 'testone', 'loggedinuser',array(
  'methods' => 'POST',
  'callback' => 'checkloggedinuser'
  ));
}); 
Run Code Online (Sandbox Code Playgroud)

6.现在再次在邮递员或应用程序中运行这个新网址以获取登录的用户详细信息。https://example.com/wp-json/testone/loggedinuser (用你的网址替换example.com)jwt令牌的使用 ( https://i.stack.imgur.com/tIqhS.png )
7.还要根据 pt.wordpress.org/plugins/jwt-authentication-for- 上的说明编辑您的 .htaccess 文件和 wp-config.php 文件wp-rest-api

  • ... 刚刚发生了什么? (4认同)

Gui*_*Gui 6

如果您更喜欢对WP REST API使用JWT身份验证,则使用Json Web Tokens可能更容易实现.

首先,验证客户端向端点发送HTTP POST请求/ wp-json/jwt-auth/v1/token发送用户名密码字段以生成身份验证令牌.

成功的回应类似于:

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9qd3QuZGV2IiwiaWF0IjoxNDM4NTcxMDUwLCJuYmYiOjE0Mzg1NzEwNTAsImV4cCI6MTQzOTE3NTg1MCwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMSJ9fX0.YNe6AyWW4B7ZwfFE5wJ0O6qQ8QFcYizimDmBy6hCH_8",
    "user_display_name": "admin",
    "user_email": "admin@localhost.dev",
    "user_nicename": "admin"
}
Run Code Online (Sandbox Code Playgroud)

然后你传递令牌每个请求设置请求头授权如:

Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9qd3QuZGV2IiwiaWF0IjoxNDM4NTcxMDUwLCJuYmYiOjE0Mzg1NzEwNTAsImV4cCI6MTQzOTE3NTg1MCwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMSJ9fX0.YNe6AyWW4B7ZwfFE5wJ0O6qQ8QFcYizimDmBy6hCH_8
Run Code Online (Sandbox Code Playgroud)