How to check username/password without signing in the user

I’m writing a plugin that creates an API endpoint that validates username/password pairs.

I’m currently using wp_signon() to check whether the username/password combo works. This works fine when the credentials fail because it returns an error object. But when the credentials are good, it automatcially signs in that user, so my endpoint returns a whole page.

The codex currently doesn’t even mention the fact that it automatically logs in the user. It also doesn’t appear to accept a parameter to suppress that functionality. For my purposes I simple boolean would be fine.

UPDATE:
I had to choose one single answer, but there was a lot of useful info several of the other answers which I’ll try to summarize briefly here…

  1. There IS a function that does exactly what I was trying to do: wp_authenticate($username, $password) HOWEVER, it comes with one drawback. It will automatically set the login cookies which can create problems in a situation like mine. So be careful. This function is not currently in the codex.

  2. The best choice for what I’m doing is wp_authenticate_username_password($user, $username, $password) because it DOESN’T set the login cookies. This function is more documented, but the REALLY important detail that wasn’t in the codex is that you can pass NULL as the first parameter. This means you can effectively use it to do exactly like wp_authenticate() without worrying about the cookies getting screwed up. Read the documentation so you don’t get confused by the response. It returns a either a WP_User object or a WP_Error (not a boolean!).

4 s
4

There is a function in the user.php of the core files called wp_authenticate_username_password that seems like what you’re looking for.

If you want to avoid throwing in the $user object (you probably only have the username + password), then just throw null as 1st function argument in:

$check = wp_authenticate_username_password( NULL, 'some_username', '#thepassw0rd' );

You can then simply check the result with is_wp_error( $check ).

Leave a Comment