3

I have a site written in PHP, and am adding new features using Python and Django. Part of this will be Django authentication using the standard contribs.auth package.

Once someone has logged in using our Django set up, when they come to the PHP side I need to see that they're logged in and use user info from the database).

What is the best way to get a user id and proof that a Django session ID is valid from PHP, using this Django sessionid cookie value?

My plan is to make a hash of the Django session id, my Django secret key, and the user id upon login. That value will be set as an additional cookie. Then in PHP, I'll extract the user id, make a hash of that and the secret key plus the Django sessionid cookie value, and compare if they match.

I extended the auth login view to set an extra cookie once a user is successfully authenticated. Instead of HttpResponseRedirect, it will return HttpResponseSetAuthCookieAndRedirect.

HttpResponseSetAuthCookieAndRedirect gets the request.session.session_id and the user_id as an argument.

class HttpResponseSetAuthCookieAndRedirect(HttpResponse):
    """ a cookie enhanced version of HttpResponseRedirect """
    status_code = 302

    def __init__(self, user_id, session_id, redirect_to):
        HttpResponse.__init__(self)
        self['Location'] = iri_to_uri(redirect_to)

        my_hash=hashlib.sha512('{0}|-|{1}|-|{2}'.format(settings.SECRET_KEY,user_id,session_id)).hexdigest()

        cookie_hash="{0}::{1}".format(user_id,my_hash[:64])

        self.set_cookie('check', value=cookie_hash, max_age=172800, path='/', domain=None)

This sets a cookie which is a hash of the session id, my Django secret key, and the authenticated user id that matches the session id.

In PHP,

$check_cookie=$_COOKIE['check'];
$django_cookie=$_COOKIE['sessionid'];

$check_cookie=str_replace('"','',$check_cookie);
$django_cookie=str_replace('"','',$django_cookie); //they have quotes for some reason

$parts=explode('::',$check_cookie);

$sent_user_id=(int)$parts[0];
$sent_hash=$parts[1];

$cookie_hash=hash('sha512',"$secret_key|-|$sent_user_id|-|$dj_cookie_sessionid");
$reconstructed_security_hash=$sent_user_id.'::'.substr($cookie_hash,0,64);

if($reconstructed_security_hash==$cookie_hash)
  {
  return $sent_user_id; //cookies are valid, and user id is the one set by Django for this session id.
  }

return false; //cookies do not match

This is working so far.

Is this idea sound?

1
  • I'm mildly new to Django by the way, so if there's some better way to do this (like by looking up the session stored in the database by the sessionid value) I'm open to suggestions.
    – Cole
    Jan 28, 2011 at 11:34

2 Answers 2

3

If you can unpickle in PHP what Django pickled into the session, then you can just grab the relevant session data directly form database (using session id from cookie), and then you'll have a direct info which user is logged in Django site - if any.

EDIT:

Here's the "encryption" Django uses:

http://code.djangoproject.com/browser/django/tags/releases/1.2.4/django/contrib/sessions/backends/base.py#L86

After "decrypting" you should get something like:

{
    '_auth_user_id': 123,
    '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend',
}

-- plus of course other session data you set yourself

3
  • Sounds good, then I could use session storage, and that probably would have been less work too. Do you know if session data is just pickled? It looks like it's Base64 encoded too. The Django documentation says the session data is 'encrypted'...
    – Cole
    Jan 28, 2011 at 14:43
  • Take a look at the link I've added above. Jan 28, 2011 at 19:12
  • Thanks for the info. It seems like accessing the session data is the best idea.
    – Cole
    Jan 29, 2011 at 14:10
0

Do you know if it is possible to build a solution that works the other way around, i.e., that makes it possible to log into an PHP app and use this login information to log into an Django app without having to type username/password again?

3
  • I actually used the method from my asnwer to log from one site to the other, Django-based, site. So yes, it's definitely possible. Jan 28, 2011 at 19:13
  • "You really should post this as a question of it's own (...)" @Cole OK, sorry for publishing my question in the wrong place. Jan 31, 2011 at 18:29
  • Yes: See this question. stackoverflow.com/questions/5023762/…
    – tobych
    Nov 29, 2014 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.