Thursday, November 29, 2012

Re: Enforce HTTPS for authenticated users but HTTP for anonymous

On Thursday, 29 November 2012 11:10:22 UTC, Tom Evans wrote:
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

Tom, that sounds like a very clean approach.  I haven't really done any middleware development yet but looking at the documentation it sounds like this shouldn't be that complicated so I might give it a bash.  Does it cause any issues if an authenticated user is redirected to HTTPS?  I assume the cookie is still sent to the server and they remain authenticated?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/Vw7Ew_qGqXgJ.
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