Wonderful world of WordPress and Django’s integration
We are preparing AnalyticalPlatform.com website. First we started showing the outputs of our “Financial research software” team on the wordpress page www.objektivni.info and then reorientated to a comprehensive Analytical Platform.
WordPress rules the world for simple yet powerful website development. To start a project, blog, simple presentation website is so simple. WordPress comes with user’s authentication, forgotten password handling, etc. It would be nice to reuse this functionality – meaning to get a username or any other related information securely… in Django.
Cookies can be shared between servers when they share the same domain name. So no problem in this area.
Obvious would be to reuse WordPress’ generated auth cookie…
WordPress authentication cookie name is concatenation for word ‘wordpress_’ and MD5 hash of the site url. The content is username, expiration and hash.
- MD5 of site url is static variable and hardly ever changes
- Username is the information we need but there is a catch – we need it securely, we need to be sure it’s from our partner server and that it is not forged
- Expiration contains timestamp when the cookie was created
- Hash is a security component. It contains hash of user login name, expiration, scheme (usually just ‘auth’) and 8th up to 12th characters from hashed user password. WordPress hashed password is made using defined variables AUTH_KEY and AUTH_SALT.
In another words without access to wordpress database with user’s hashed passwords we are unable to check authenticity of auth cookie from WordPress.
WordPress has an easy way how to add functionalities through plugins. Plugins can call add_action to register or inject specific functionality to the site.
We created a new plugin which injects a call to set our own cookie. It sets the cookie right after a user logs in to the wordpress – action ‘wp_login’.
Luckily PHP contains cryptographic libraries included by default. We create a content of the cookie using symmetric cryptography using Counter (CTR) mode. Additional measures are taken in, like random initialization vector and HMAC for message integrity check.
Right now we just store the username in the cookie. Using our own cookie allows to share any wordpress’ desirable information in the future.
Technical detail – PHP has two functions to set a cookie. ‘setcookie’ url-encodes the value of the cookie, to set a cookie exactly we use ‘setrawcookie’.
The Django side
Django and WordPress shares the secret key only. The cookie is automatically delivered to all servers within the same domain.
Django tries to get specific cookie from the request, decrypts it, check for integrity and returns the username if all is fine.