如何使用JWT身份验证获取登录的用户信息?

时间:2019-04-10 09:16:30

标签: php wordpress jwt wordpress-rest-api

在我的WordPress REST API项目中,我需要通过api登录用户数据。我使用了JWT Authentication for WP REST API插件来生成令牌。我已经使用用户名和密码作为参数生成令牌。 enter image description here

现在我使用此标记在api文件中创建了一个函数,但它向我发送了0作为邮递员的api响应,并带有以下标头。

'Content-type': 'application/json', 
'Authorization': 'Bearer token_value'

功能代码:

function get_loggedin_user_info(){
  global $current_user; 

  $current_user = wp_get_current_user();
  print_r($current_user);
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'endpoints/v1', '/logininfo', array(
            'methods' => 'POST',
            'callback' => 'get_loggedin_user_info'
    ));
});

那么我如何使用WordPress钩子wp_get_current_user()

获取登录的用户数据?

第二,如何使jwt-auth/v1/token API可以将用户名和密码设置为动态?

P.S我已经在htacceess文件中添加了RewriteCond和RewriteRule,并且还在我的配置文件中包含了JWT Auth Secret密钥。

define('JWT_AUTH_SECRET_KEY', 'secret-key');
define('JWT_AUTH_CORS_ENABLE', true);

2 个答案:

答案 0 :(得分:1)

您可以使用以下路线:/wp-json/wp/v2/users/me

将令牌发送到此路由并获取用户的详细信息

如果您有任何问题,我在这里:)

答案 1 :(得分:0)

请注意,成功登录后,您还可以修改JWT响应:

function mod_jwt_auth_token_before_dispatch( $data, $user ) {
    $user_info = get_user_by( 'email',  $user->data->user_email );
    $profile = array (
        'id' => $user_info->id,
        'user_first_name' => $user_info->first_name,
        'user_last_name' => $user_info->last_name,
        'user_email' => $user->data->user_email,
        'user_nicename' => $user->data->user_nicename,
        'user_display_name' => $user->data->display_name,
        'phone' => get_field( 'phone', "user_$user_info->id" ) // you also can get ACF fields
    );
    $response = array(
        'token' => $data['token'],
        'profile' => $profile
    );
    return $response;
}
add_filter( 'jwt_auth_token_before_dispatch', 'mod_jwt_auth_token_before_dispatch', 10, 2 );

这样,您无需调用另一个端点即可从用户那里获取更多数据。

当用户返回您的网站/应用程序时,请记住首先验证令牌,然后好的方法是调用/users/me端点。

同样,如果您想返回有关users/me的更多信息,可以这样做:

function add_custom_fields() {
        register_rest_field(
            'user', 
            'profile',
            array(
                'get_callback'    => 'get_custom_fields',
                'update_callback' => null,
                'schema'          => null,
            )
        );
    }
    add_action( 'rest_api_init', 'add_custom_fields' );

    function get_custom_fields( $object, $field_name, $request ) {
        $user_info = get_user_by( 'id',  $object['id'] );
        $profile = array (
            'id' => $user_info->id,
            'user_first_name' => $user_info->first_name,
            'user_last_name' => $user_info->last_name,
            'user_email' => $user_info->user_email,
            'user_nicename' => $user_info->user_nicename,
            'user_display_name' => $user_info->display_name,
        );
        return $profile;
    }
相关问题