简体   繁体   English

通过 REST API 登录 WP 用户

[英]Login a WP user via REST API

I have two websites:我有两个网站:

  • site.com (WordPress site) site.com(WordPress 网站)
  • subdomain.site.com (another site) subdomain.site.com(另一个站点)

I want to login a WP user in site.com (WP) from subdomain.site.com using WP REST API.我想从 subdomain.site.com 使用 WP RESTADB94FZ8DE7D1C50Z 登录 site.com (WP) 中的 WP 用户

So, I do the following in functions.php in site.com (WP):因此,我在 site.com (WP) 中的 functions.php 中执行以下操作:

add_action('rest_api_init', function () {
    register_rest_route('xxx/v1', '/login', [
        'methods'   => WP_REST_Server::READABLE,
        'callback'  => function (WP_REST_Request $request) {
            // I try this:
            wp_set_current_user(1);
            wp_set_auth_cookie(1);

            // and this:
            $user = wp_signon([
                'user_login' => 'xxx',
                'user_password' => 'xxx',
                'remember' => true,
            ], false);
        }
    ]);
});

And in subdomain.site.com, I use CURL to make the request.在 subdomain.site.com 中,我使用 CURL 提出请求。

Unfortunately, it doen't work.不幸的是,它不起作用。 The code is well executed but user login does not work, cookies are not defined.代码执行良好,但用户登录不起作用,cookies 未定义。

Can you help?你能帮我吗?

Thanks!谢谢!

Have you tried the following:您是否尝试过以下方法:

add_action( 'rest_api_init', 'register_api_hooks' );

function register_api_hooks() {
  register_rest_route(
   'xxx/v1', '/login',
    array(
      'methods'  => 'POST',
      'callback' => 'login',
    )
  );
 }

function login($request){
    $creds = array();
    $creds['user_login'] = $request["username"];
    $creds['user_password'] =  $request["password"];
    $creds['remember'] = true;
    $user = wp_signon( $creds, false );

    if ( is_wp_error($user) )
      echo $user->get_error_message();

     return $user;
}

add_action( 'after_setup_theme', 'custom_login' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM