Thursday, November 29, 2012

Re: Enforce HTTPS for authenticated users but HTTP for anonymous

On Thu, Nov 29, 2012 at 9:32 AM, Roarster <ianstrachan2008@gmail.com> wrote:
> Is there any easy way to have a django site enforce HTTPS for authenticated
> users while any anonymous users would default to HTTP? This would allow me
> to protect the sessions and cookies for users who have logged on while
> conserving server resources for those who aren't authenticated (I would
> assume the majority of connections). As part of this it would also make
> sense for me to ensure the login and register pages also use HTTPS to
> protect any passwords.
>
> I'm not sure if it's relevant but I'm using Nginx as a web server with uwsgi
> dealing with the django requests.
>
> Thanks.
>

Write some custom middleware to handle your logic. We have a similar
requirement at $JOB - SSL on logins, preference pages, anything with a
password form on it, but not on other views. I can't show the code,
but I can describe the logic.

You actually need to specify two things for a URL - is SSL allowed,
and is SSL required.
Your middleware should hook in to process_request.
If the current request is not SSL, check if the URL requires SSL and
redirect to SSL if it does.
If the current request is SSL, check if SSL is allowed, redirect to
non SSL if it doesn't.
If the request is a POST and needs redirection, blow up, this is a
logic error (you can't redirect a POST, and anything requiring this is
doing things in an incorrect order).

There is an easy way to check if SSL is required for a view. In your
urlconf, you can specify additional keyword arguments for a view. Our
middleware checks for the keyword arguments 'ssl_required' and
'ssl_allowed', which neatly allows the configuration for whether a URL
is to be handled by SSL to be included along with all the other URL
configuration.

An important note is that the middleware must remove these additional
arguments, since the views will not be expecting them!

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment