Repository navigation
Conversation
Adds POST /two-factor/1.0/login and POST /two-factor/1.0/revalidate so custom front-ends can complete the second factor and revalidate a session without the wp-login.php screens. Both run through the same provider processing as the forms; providers receive REST codes through validate_authentication_code() with a request-based fallback. Fixes WordPress#1044
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the Unlinked AccountsThe following contributors have not linked their GitHub and WordPress.org accounts: @chubes4. Contributors, please read how to link your accounts to ensure your work is properly credited in WordPress releases. If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message. To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. |
Two_Factor_Core::verify_authentication_code() verifies a code for any authentication integration (bearer tokens, headless logins) with the same processing as the forms, returning true, a code_sent result, or a WP_Error. get_login_challenge() describes the challenge. The two_factor_current_session_two_factor_time filter lets non-cookie sessions report when they passed two-factor, so they can manage settings and use POST /revalidate. Revalidation-required errors carry data.revalidation.
This was referenced Nov 17, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What?
Lets any authentication integration complete Two-Factor without a stock
wp-login.phpor Two Factor screen, including clients that authenticate with bearer tokens (native and headless apps) rather than cookies:Two_Factor_Core::verify_authentication_code( WP_User $user, string $provider_key, array $args ): public, non-rendering verification. Returnstrue,array( 'status' => 'code_sent' )after a resend, or a structuredWP_Error.Two_Factor_Core::get_login_challenge( WP_User $user ): returns{ provider, providers: [{ key, label }] }for the challenge prompt.two_factor_current_session_two_factor_timefilter (int|false $time, WP_User $user): lets non-cookie sessions report when they passed two-factor. It drives the revalidation grace checks, so token sessions can manage settings (Add REST provider management and server-owned TOTP enrollment #935) and revalidate.POST /two-factor/1.0/login: the cookie login route, which completes the second factor for a pending login using the login nonce.POST /two-factor/1.0/revalidate: revalidates the current session, cookie or token.data.revalidation = { required: true, rest_route: '/two-factor/1.0/revalidate', url }and status 403.Fixes #1044
Why?
Today the second factor can only be completed on
wp-login.php?action=validate_2fa, and changing settings outside the grace window needswp-login.php?action=revalidate_2fa. Sites that keep members away from stock WordPress screens either expose those screens just for 2FA or re-implement nonce checks, rate limiting, failed-attempt accounting and session flags themselves.The first version of this PR only covered cookie clients. A native app that authenticates with bearer tokens can't use a route that sets a cookie. It needs a verification call that returns data instead of rendering a page. And
current_user_can_update_two_factor_options()only reads cookie session metadata, so a token session could never manage settings or revalidate (it gottwo_factor_session_required). The expanded scope is described in #1044 (comment).This complements #935 (REST provider management and server-owned TOTP enrollment, #934). With the filter, a token session can call #935's routes, and when the grace window has passed it can revalidate in place through
/revalidate.How?
One verification path
process_provider_attempt()(private) holds the rate limiting, pre-processing (resend), validation, failed-attempt accounting,wp_login_failedand the compromised-password reset. Nothing is rendered there.process_provider(). Providers read the form fields as before.verify_authentication_code()passes the code andresendin as arguments. Providers receive them throughvalidate_authentication_code()andpre_process_authentication_with_args().verify_authentication_code().wp_login_failednow fires insideprocess_provider_attempt()for invalid and rate-limited attempts, instead of in each caller. The forms fire it exactly as before, and the REST routes and direct callers now get it too.two_factor_password_reset_required.process_provider()still rendersshow_password_reset_error()and exits for the form path, so form behavior and messages are unchanged.complete_two_factor_login()) and revalidation bookkeeping (complete_two_factor_revalidation()) are shared by the forms and the REST handlers.verify_authentication_code()contract$args:code(string),resend(bool). Nothing is read from$_REQUEST, nothing is output, and it never exits. An empty$provider_keyuses the primary provider. A requested provider the user hasn't enabled is an error, not a silent fallback.truearray( 'status' => 'code_sent' )resend). Not counted as a failure.two_factor_invalid(401)wp_login_failedfired.two_factor_too_fast(429)data.retry_afterin seconds. Attempt not counted.two_factor_provider_not_enabled(400)two_factor_password_reset_required(403)two_factor_provider_missing(403)It must only be called after the user's password (or other primary credential) has been verified.
Non-cookie sessions
get_current_session_two_factor_time()defaults to the cookie session'stwo-factor-loginmetadata and appliestwo_factor_current_session_two_factor_time. If nothing hooks the filter, behavior is unchanged. A token plugin returns the time its session passed or last revalidated two-factor,0for a known session that hasn't passed two-factor yet (it may still revalidate), orfalsefor no session.is_current_user_session_two_factor(), and with itcurrent_user_can_update_two_factor_options()andmaybe_mark_current_session_two_factor(), read the filtered value./revalidateaccepts a request that has a cookie session or a non-false filtered time. Other requests (for example application passwords, or tokens nobody reports) still get400 two_factor_session_required. On success it firestwo_factor_user_revalidated( $user, $provider ), which is where token plugins record the new time. The cookie session metadata is only updated when a cookie session exists.update_current_user_session()now returns false instead of erroring when the token has no stored session.Endpoint contract
POST /two-factor/1.0/login(public; the login nonce is the credential):user_id,login_nonce, optionalprovider,code,resend,remember,redirect_to.401 two_factor_invalid_login_nonce, one message for all cases, no new noncecodeand noresend200 {result: "challenge", user_id, provider, providers: [{key, label}], login_nonce, expires}resendhandled by the provider200 {result: "code_sent", ...same fields}401 two_factor_invalid,data.login_nonce/data.expires429 two_factor_too_fast,data.retry_after+Retry-Afterheader, new nonce400 two_factor_provider_not_enabled+ new nonce403 two_factor_password_reset_required; pending login nonce deleted200 {result: "authenticated", user_id, provider, redirect_to}plus auth cookiesEvery non-success response after the nonce is verified rotates the nonce, as the form does when it re-renders.
redirect_togoes through the form'slogin_redirectand capability fallback, thenwp_validate_redirect().POST /two-factor/1.0/revalidate(logged in): optionalprovider,code,resend. Returns401 rest_not_logged_inwhen logged out and400 two_factor_session_requiredas described above. It gives the same challenge,code_sentand error responses as/login, without nonce fields. On success it returns200 {result: "revalidated", user_id, provider, two_factor_login}. Cookie-authenticated REST requests already require thewp_restnonce, which replaces the form's revalidation nonce.Provider methods (backwards compatible)
validate_authentication_code( $user, $code ): the default falls back tovalidate_authentication( $user ), so third-party providers keep working. TOTP, Email and Recovery Codes override it and normalize the code the same way their form fields do.pre_process_authentication_with_args( $user, $args ): the default falls back topre_process_authentication(). Email sends a new code whenresendis true.Two_Factor_Provider::sanitize_code(): the value-based counterpart ofsanitize_code_from_request().Security parity
/logindeletes the pending login nonce. The form path is unchanged.Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude
Used for: Repository investigation, implementation, tests, and PR drafting. The shared path was checked against the existing form handlers, provider methods and form-flow tests.
Testing Instructions
tests/class-two-factor-rest-login-api.phpcovers/loginand/revalidate. New for token sessions:two_factor_user_revalidatedwith no cookie session0(not yet two-factor) may revalidatewp_login_failedand not the revalidated actiontwo_factor_session_requiredNew
tests/class-two-factor-verification-api.phpcovers:verify_authentication_code(): success with no output and no login, primary-provider default,$_REQUESTignored, invalid (401, failure counted,wp_login_failed), rate limited (429 +retry_after, not counted), provider not enabled (400), password reset required (403, password changed, no output), and email resend (code_sent, then the code validates)get_login_challenge()with and without two-factortime()) canDELETE /two-factor/1.0/totp, which without the filter fails with403 revalidation_requiredcarryingdata.revalidation.rest_route; the grace window still applies to the filtered timeThe existing form-flow tests (
process_provider,validate_login_form_2fa,revalidate_login_form_2fa) pass unchanged.Run in
wp-env:composer test-single: OK (396 tests, 1568 assertions)composer test-multisite: OK (396 tests, 1568 assertions)composer lint(PHPCS),composer lint-phpstan,composer lint-compat(PHP 7.2+): passManual (token integration): after verifying the password, call
Two_Factor_Core::get_login_challenge( $user ), show the prompt, thenTwo_Factor_Core::verify_authentication_code( $user, $provider, array( 'code' => $code ) )and issue your token ontrue. Hooktwo_factor_current_session_two_factor_timeto return your session's verified-at time, andtwo_factor_user_revalidatedto update it.Changelog Entry
Written directly by Extra Chill Bot (AI agent) for Chris Huber.