Implement TOTP Two-Factor Authentication in WordPress Without a Plugin

Implement TOTP two-factor authentication in WordPress without a plugin

Time-based one-time passwords (TOTP, RFC 6238) are what authenticator apps (Google Authenticator, Authy, 1Password) generate: a 6-digit code computed from a shared secret and the current time in 30-second steps. The server runs the same algorithm, so no third-party service is involved. A stolen or reused password is no longer enough to log in, which is exactly what credential-stuffing attacks rely on.

Problem: One of eight admin accounts of a law firm’s site was compromised with a password reused from another site’s data breach. Two-factor authentication must become mandatory for everyone who can edit content.

Solution: Generate a secret per user, let the user add it to an authenticator app, add a code field to the login form, and check the code on the authenticate filter after the password, rejecting reused codes.

This is a reference implementation to show how it works. For a production site, the Two Factor plugin from the WordPress.org directory (maintained by core contributors) or a reviewed library such as spomky-labs/otphp is the safer choice.

The algorithm

<?php
class MyPlugin_TOTP {
    const PERIOD = 30;
    const DIGITS = 6;

    public static function generate_secret() {
        return self::base32_encode( random_bytes( 20 ) );
    }

    // Returns the matched time step, or false. Accepts one step of clock drift.
    public static function verify( $secret, $code ) {
        if ( ! preg_match( '/^\d{6}$/', $code ) ) {
            return false;
        }
        $key  = self::base32_decode( $secret );
        $step = (int) floor( time() / self::PERIOD );

        foreach ( array( -1, 0, 1 ) as $offset ) {
            if ( hash_equals( self::code_at( $key, $step + $offset ), $code ) ) {
                return $step + $offset;
            }
        }
        return false;
    }

    public static function code_at( $key, $step ) {
        $hash   = hash_hmac( 'sha1', pack( 'J', $step ), $key, true );
        $offset = ord( $hash[19] ) & 0x0F;
        $number = ( ( ord( $hash[ $offset ] ) & 0x7F ) << 24 )
                | ( ord( $hash[ $offset + 1 ] ) << 16 )
                | ( ord( $hash[ $offset + 2 ] ) << 8 )
                | ord( $hash[ $offset + 3 ] );
        return str_pad( (string) ( $number % ( 10 ** self::DIGITS ) ), self::DIGITS, '0', STR_PAD_LEFT );
    }

    private static function base32_encode( $data ) {
        $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
        $out = '';
        $buffer = 0;
        $bits = 0;
        foreach ( str_split( $data ) as $byte ) {
            $buffer = ( ( $buffer << 8 ) | ord( $byte ) ) & 0xFFFF;
            $bits  += 8;
            while ( $bits >= 5 ) {
                $bits -= 5;
                $out  .= $alphabet[ ( $buffer >> $bits ) & 0x1F ];
            }
        }
        if ( $bits > 0 ) {
            $out .= $alphabet[ ( $buffer << ( 5 - $bits ) ) & 0x1F ];
        }
        return $out;
    }

    private static function base32_decode( $data ) {
        $map = array_flip( str_split( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' ) );
        $out = '';
        $buffer = 0;
        $bits = 0;
        foreach ( str_split( strtoupper( $data ) ) as $char ) {
            if ( ! isset( $map[ $char ] ) ) {
                continue;
            }
            $buffer = ( ( $buffer << 5 ) | $map[ $char ] ) & 0xFFFF;
            $bits  += 5;
            if ( $bits >= 8 ) {
                $bits -= 8;
                $out  .= chr( ( $buffer >> $bits ) & 0xFF );
            }
        }
        return $out;
    }
}

hash_equals() compares in constant time, so the response time does not leak how many digits were right. The implementation matches the RFC 6238 test vectors.

Setup in the user profile

The user scans a QR code (or types the secret) in the app. The QR code contains an otpauth:// URI; to keep the secret off third-party servers, render it with a local JavaScript QR library from this URI rather than an online QR service:

<?php
add_action( 'show_user_profile', function ( $user ) {
    $secret = get_user_meta( $user->ID, '_myplugin_totp_pending', true );
    if ( ! $secret ) {
        $secret = MyPlugin_TOTP::generate_secret();
        update_user_meta( $user->ID, '_myplugin_totp_pending', $secret );
    }
    $uri = sprintf(
        'otpauth://totp/%s:%s?secret=%s&issuer=%s',
        rawurlencode( get_bloginfo( 'name' ) ),
        rawurlencode( $user->user_login ),
        $secret,
        rawurlencode( get_bloginfo( 'name' ) )
    );
    ?>
    <h2><?php esc_html_e( 'Two-factor authentication', 'myplugin' ); ?></h2>
    <p><?php esc_html_e( 'Add this key to your authenticator app, then enter the current code to confirm:', 'myplugin' ); ?></p>
    <p><code><?php echo esc_html( $secret ); ?></code></p>
    <div id="myplugin-totp-qr" data-uri="<?php echo esc_attr( $uri ); ?>"></div>
    <p><input type="text" name="myplugin_totp_confirm" inputmode="numeric" autocomplete="one-time-code" maxlength="6"></p>
    <?php
} );

add_action( 'personal_options_update', function ( $user_id ) {
    // The profile form already carries WordPress' own nonce, checked before this hook
    $code    = sanitize_text_field( wp_unslash( $_POST['myplugin_totp_confirm'] ?? '' ) );
    $pending = get_user_meta( $user_id, '_myplugin_totp_pending', true );

    if ( $code && $pending && false !== MyPlugin_TOTP::verify( $pending, $code ) ) {
        update_user_meta( $user_id, '_myplugin_totp_secret', $pending );
        delete_user_meta( $user_id, '_myplugin_totp_pending' );
    }
} );

The secret becomes active only after the user proved with a code that the app has it, so nobody locks themselves out with a mistyped key.

The code at login

<?php
// A code field on the login form
add_action( 'login_form', function () {
    echo '<p><label for="myplugin_totp">' . esc_html__( 'Authentication code', 'myplugin' ) . '</label>'
       . '<input type="text" name="myplugin_totp" id="myplugin_totp" class="input" inputmode="numeric" autocomplete="one-time-code" maxlength="6"></p>';
} );

// After the password check (priority 20), before the login completes
add_filter( 'authenticate', function ( $user ) {
    if ( ! ( $user instanceof WP_User ) ) {
        return $user; // wrong password: WordPress reports it
    }

    $secret = get_user_meta( $user->ID, '_myplugin_totp_secret', true );
    if ( ! $secret ) {
        return $user; // 2FA not set up yet
    }

    $code = sanitize_text_field( wp_unslash( $_POST['myplugin_totp'] ?? '' ) );
    $step = MyPlugin_TOTP::verify( $secret, $code );

    // Each code works once: reject the same or an older time step
    if ( false === $step || $step <= (int) get_user_meta( $user->ID, '_myplugin_totp_last_step', true ) ) {
        return new WP_Error( 'myplugin_totp_invalid', __( '<strong>Error:</strong> Invalid authentication code.', 'myplugin' ) );
    }

    update_user_meta( $user->ID, '_myplugin_totp_last_step', $step );
    return $user;
}, 30 );

A one-step form (password and code together) is simpler than a separate second screen and has no half-authenticated state to protect. The _last_step check is the replay protection the RFC requires: a code seen by someone over the user’s shoulder cannot be used again.

Making it mandatory

<?php
add_action( 'admin_init', function () {
    $user = wp_get_current_user();
    if ( wp_doing_ajax() || ! current_user_can( 'edit_posts' ) || get_user_meta( $user->ID, '_myplugin_totp_secret', true ) ) {
        return;
    }
    if ( 'profile.php' !== $GLOBALS['pagenow'] ) {
        wp_safe_redirect( admin_url( 'profile.php#myplugin-totp-qr' ) );
        exit;
    }
} );

Users who can edit content are sent to their profile until 2FA is set up.

NOTE: Two things are left out to keep the example short and are needed in production: recovery codes (ten random one-time codes, stored hashed with wp_hash_password()), and encryption of the secret at rest (for example sodium_crypto_secretbox() with a key from wp-config.php), so a database dump does not expose the secrets. Application Passwords for the REST API are checked separately and bypass this filter by design, so restrict who may create them; XML-RPC logins with the normal password, on the other hand, now fail without a code, which is usually what you want. Rate limiting the login form, as in preventing brute force attacks, also applies to the code field.