usefulteam / jwt-auth

WordPress JSON Web Token Authentication
https://wordpress.org/plugins/jwt-auth/
124 stars 50 forks source link

Function to generate a token for a user (public API) #26

Open psaikali opened 3 years ago

psaikali commented 3 years ago

First of all, thank you for developing this plugin! It's really great. I'm using it to authenticate users from a React Native app.

I'm creating my own API route for that, where I directly call the generate_token() method on the JWTAuth\Auth class, like so:

public function process() {
    $login    = sanitize_text_field( $this->get_param( 'login' ) );
    $password = sanitize_text_field( $this->get_param( 'password' ) );
    $user     = wp_authenticate( $login, $password );

    if ( is_wp_error( $user ) ) {
        return $user;
    }

    $auth    = ( new \JWTAuth\Auth() )->generate_token( $user, false );
    $payload = apply_filters( 'project/ajax/user-login/payload', $auth['data'], $user );

    return [
        'success' => true,
        'auth'    => $payload,
    ];
}

So far so good, but I'm wondering if it would be safer and more practical for everybody if we had access to a basic function to generate the token, instead of instantiating the class and calling the right method. Maybe something like jwtauth_generate_token( $user, false ).

That way, it's update-proof: if something changes (class name, method, parameters), we make sure to reflect these changes in the publicly available function, so we ensure long-term compat.

What do you think?

I can take care of creating such a function and add a PR if necessary.

pesseba commented 3 years ago

Hi @psaikali, you can use the request endpoint in wp like this:

//override for current user token generation
add_filter( 'authenticate', function($user, $name, $pwd){ return wp_get_current_user(); }, 999, 3);                         

//api call
$r = new WP_REST_Request( 'POST', '/jwt-auth/v1/token');
$response = rest_do_request( $r );