get token using the 'WordPress REST API with JWT Authentication' plugin

I'm trying to build a Wordpress plugin that is an API which can be queried from remote websites.

I want to secure it with JWT web tokens, so I did install the JWT Authentication for WP REST API plugin. I read this article to configure it, and have a working setup (checked in Postman).

So I have my API website with JWT working.

Now, I want to request that API from the client website.

I need a token from the API website to be able to request it from outside. So, first, I need to generate that token when my user register and logs in on the API website.

I started to write some code but I'm stuck. Once the user is logged in, how can I make a post request to get the token ?

Also, is this the right way to process ? Generate a token on the API website and use it on the client website ? How/when will the token expire ?

Thanks!

add_action( 'init', array($this,'generate_user_token') );

public function generate_user_token(){
    $token = $this-get_token();
    if( is_wp_error($token) ) return $token;

    //store and show token so user can user it on client side.
}

private function get_token(){

    if ( !$user_id = get_current_user_id() ){
        return new WP_Error('user_not_logged','Cannot get token, user is not logged');
    }

    $args = array(
        'body' = array( 
            'username' = //how could I fill this parameters required by JWT-AUTH ?
            'password' = //how could I fill this parameters required by JWT-AUTH ?
        ),
    );

    $request = wp_remote_post( get_rest_url(null,'jwt-auth/v1/token'), $args );
    if (is_wp_error($request)) return $request;

    $response = wp_remote_retrieve_body( $request );
    if (is_wp_error($response)) return $response;

    $response = json_decode($response, true);

    //check for errors
    $code = ( isset($response['code']) ) ? $response['code'] : null;
    $message = ( isset($response['message']) ) ? $response['message'] : null;
    $data = ( isset($response['data']) ) ? $response['data'] : null;
    $status = ( isset($data['status']) ) ? $data['status'] : null;

    if ( $code  ($status = 400) ){
        return new WP_Error($code,$message,$data );
    }

    return $response['token'];

}

}

Topic authentication wp-remote-request rest-api Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.