Someone asked this over at http://wordpress.stackexchange.com and I put a lot of research into it, so I figured I’d post it here too.

Someone had asked how to go about securing RSS feeds behind a firewall in WordPress. It’s not an overly easy process so I dug in to try and figure it out.

I knew that WordPress had a lot of action hooks, little pieces of code that a developer (like you) can tie into to change how WordPress behaves. This is how all these great plugins can change core functionality of WordPress when you install them.

I knew there had to be a hook for displaying feeds and all I needed to do was to find that hook and run some authentication checks before the feed was displayed. I worked on that, tested it and here was my answer.

There is a solution as described here where you can put code at the top of wp-includes/feed-rss2.php to authenticate that the requester is a registered WordPress user. A better solution is to add it to your theme’s functions.php file:

function my_check_feed_auth() {
    if (!isset($_SERVER['PHP_AUTH_USER'])) {
        header('WWW-Authenticate: Basic realm="RSS Feeds"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Feeds from this site are private';
        exit;
    } else {
        if (is_wp_error(wp_authenticate($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']))) {
            header('WWW-Authenticate: Basic realm="RSS Feeds"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'Username and password were not correct';
            exit;
        }
    }
}

add_action('do_feed_rss2', 'my_check_feed_auth', 1);
add_action('do_feed_atom', 'my_check_feed_auth', 1);
add_action('do_feed_rss', 'my_check_feed_auth', 1);
add_action('do_feed_rdf', 'my_check_feed_auth', 1);

This will require Basic Auth, which most RSS readers can configure, with the user’s WordPress login information. You can add more feeds on to the end there with more add_action calls, if you want.