Quantcast
Channel: mdgArt » Auth
Viewing all articles
Browse latest Browse all 2

Django Auth behind proxy server

$
0
0

Yesterday I had a weird problem with a Django application that should primarily work on computer behind a proxy server: for some reason that I didn’t understand yet, the proxy lost the session’s cookie, but only when a form send data (via POST) to a view that is visible only to logged users (=O).
The other views works well, but that particular views lost the cookie! What to do in this case?
A simple workaround helped me: I sent the session id via GET to the view. I know, django never use this for security reason, but I didn’t find a “official” solution, so this is what I did:

I create this middleware that use the query string session id if it doesn’t find the session’s cookies in the request:

from django.conf import settings
 
class FakeSessionCookieMiddleware(object):
 
    def process_request(self, request):
        if not request.COOKIES.has_key(settings.SESSION_COOKIE_NAME) and request.GET.has_key(settings.SESSION_COOKIE_NAME):
            request.COOKIES[settings.SESSION_COOKIE_NAME] = request.GET[settings.SESSION_COOKIE_NAME]

You have to add this middleware to your settings.py before django.contrib.sessions.middleware.SessionMiddleware:

MIDDLEWARE_CLASSES = (
    ...
    'myapp.middleware.FakeSessionCookieMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
)

In this case the middleware class is inside the middleware.py file in myapp application.
Then you can add SESSION_COOKIE_NAME in your context like this:

context = {
    'session_cookie_name': settings.SESSION_COOKIE_NAME,
    'session_cookie_value': request.COOKIES[settings.SESSION_COOKIE_NAME], 
} 
    template = 'yourtemplate.html' 	
    return render_to_response(template, context, context_instance=RequestContext(request))

and pass “session_cookie_name” and “session_cookie_value” in your URL:

<a href="/your/url/?{{session_cookie_name}}={{session_cookie_value}}">

Is ugly and potentially dangerous, but it’s an extreme solution in case you REALLY have this problem that can’t be solved in other ways. Hope this can help someone with the same issue.

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images