jwt-auth icon indicating copy to clipboard operation
jwt-auth copied to clipboard

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

Open psaikali opened this issue 4 years ago • 1 comments

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.

psaikali avatar Mar 04 '21 17:03 psaikali

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 );

pesseba avatar Mar 04 '21 19:03 pesseba