Search code examples
c#wordpresshttpmodule

How to access WordPress logged in username via C# HttpModule


I have a simple HttpModule that I want to use to control access to certain content on my WordPress site. Some details are available at How to restrict access to WordPress content in .NET/PHP application.

To do this I need to be able to determine the username associated with any request. How do I do that?


Solution

  • Using the details at http://codex.wordpress.org/WordPress_Cookies, and http://msdn.microsoft.com/en-us/library/system.web.httprequest.cookies(v=vs.110).aspx I wrote a simple method that gets the WP login cookie from the incoming request. The basic outline is given by:

    private static String GetWpLoginCookie(HttpContext context)
    {
        String[] cookieKeys = context.Request.Cookies.AllKeys;
        foreach (var cookieKey in cookieKeys)
        {
            if (cookieKey.StartsWith("wordpress_logged_in"))
            {
                return WebUtility.UrlDecode(context.Request.Cookies[cookieKey].Value);
            }
        }
        return "Not found";
    }
    

    I can now get the username by from loginCookie.Split('|')[0].