Search code examples
wordpressoauth-2.0http-authenticationmod-perl

How to proxy per-request WordPress user authentication data to another server in the same domain?


I’m using WordPress as my frontend for user administration, handling registration, logins, authentication and logouts. Users register and login using WordPress.

The site has URLs served by a backend mod_perl server in the same domain. When a user clicks a link that proxies to the backend server, I would like for the frontend server, the proxy, to pass the authenticated user’s name or login credentials to the backend server. The backend server will use those credentials to do authorization. I can imagine several ways to do this.

  1. Maybe the backend server reads the username from the WordPress cookie. The Cookie HTTP Header is visible in the backend server logs (I configured intentionally this as a debugging aid.) Is it possible to do this, one server read a cookie written by another server (in the same domain)?

    The frontend WordPress server might write the authenticated username into an environment variable which mod_rewrite would tack on to the URL proxiing to the backend server. Maybe using a WordPress plugin, but I’ve not found such.

    WordPress SSO/OAuth might be possible, but my OS X El Capitan development environment presents another layer of challenges for that.

The frontend is Apache2.4, PHP 5.5.34, WordPress 4.5.3. Apache modules can be added and removed as DSOs. The backend is Apache 2.4, mod_perl 2.0.10, MySQL 5.7.

Both servers run in the same AWS instance running AWS Linux. (I’m beginning to think AWS Linux was the wrong choice for me, but that’s a whole nother thread.)

I have Apache, MySQL and Perl skills. PHP and Javascript I never learnt.


Solution

  • The simplest way (perhaps it's also the only practicable one) would be to use PHP because wordpress is a PHP application, which indeed is a problem for you. Nevertheless, I have a simple example for you:

    PHP page on your wordpress site:

    <?php
    require('path/to/wp-blog-header.php');
    
    if (is_user_logged_in()) {
        $user = wp_get_current_user();
        header("Location:backend.php?user=".$user);
        exit();
    } else {
        echo "User is not logged in!";
    };
    ?>
    

    PHP page on your backend server:

    <?php
    if (isset($_GET['user'])) {
        $user = $_GET['user'];
        // do something with $user.
    } else {
        echo "No user passed!";
    }
    ?>
    

    This simply uses two of Wordpress' built-in functions. First the is_user_logged_in() function is used to determine whether a user is logged in. If the function returns true, the wp_get_current_user() function is called to pass the username to the backend server's php page using the GET method. Then the backend server validates the passed variable.

    Please note that this simple procedure is illustrative only and is extremely unsafe!