OiO.lk Blog security How to protect sensitive user-configurable settings in a WordPress plugin?
security

How to protect sensitive user-configurable settings in a WordPress plugin?


I am creating a WordPress plugin that query a third-party API using an authentication token. The plugin requires the website administrator/plugin user to configure the token. In its current state, the plugin exposes the token in a settings page which stores the value in the wp_options table.

Here is a simplified version:

class Foobar_Plugin {
    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
    }

    public function add_settings_page() {
        add_options_page(
            __( 'Foobar Settings', 'foobar-plugin' ),
            __( 'Foobar', 'foobar-plugin' ),
            'manage_options',
            'foobar-settings',
            array( $this, 'render_settings_page' )
        );
    }

    public function register_settings() {
        register_setting(
            'foobar_settings',
            'foobar_api_token',
            array(
                'type'              => 'string',
                'sanitize_callback' => 'sanitize_text_field',
                'default'           => '',
            )
        );

        add_settings_section(
            'foobar_settings_section',
            __( 'Foobar Settings', 'foobar-plugin' ),
            null,
            'foobar-settings'
        );

        add_settings_field(
            'foobar_api_token',
            __( 'API Token', 'foobar-plugin' ),
            array( $this, 'api_token_field_callback' ),
            'foobar-settings',
            'foobar_settings_section'
        );
    }

    public function api_token_field_callback() {
        $api_token = get_option( 'foobar_api_token', '' );
        printf(
            '<input type="text" id="foobar_api_token" name="foobar_api_token" value="%s" class="regular-text" />',
            esc_attr( $api_token )
        );
        echo '<p class="description">' . __( 'Enter your API Token.', 'foobar-plugin' ) . '</p>';
    }
}

What options do I have in order for the token to be hard for an attacker to access while still allowing the website administrator to configure the token easily?

A slight improvement would be to only allow the user to set this token without being able to read it back from the settings page. However, I am looking for a more secure option in addition to this.

What options are there? How do other plugins (or WordPress) handle this case? I was thinking about encrypting/decrypting the token stored in wp_options using one (or a combination of) keys stored in wp-config.php.



You need to sign in to view this answers

Exit mobile version