SSL Force Middleware
A simple way to force SSL on all pages. It's very simple at this point - the only issue I can see right now and I will address this later is if someone sends http:// in another portion of your url.
- middleware
- django
- ssl
- secure
A simple way to force SSL on all pages. It's very simple at this point - the only issue I can see right now and I will address this later is if someone sends http:// in another portion of your url.
This middleware redirects HTTP requests to HTTPS for some specified URLs, in the same way as [85](http://djangosnippets.org/snippets/85/). It also changes the `url` template tag to use the `https` scheme for the same URLs. For example, if you have the following URL pattern: url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'https': True}) then the template: {% from future import url %} {% url 'django.contrib.auth.views.login' %} will render: https://host.example.com/accounts/login/ and any plain HTTP requests to /accounts/login get redirected to HTTPS. URL patterns not marked with `'https': True` remain unaffected. Notes: * The HttpRequest object must be present in the template context as `request`, so add `django.core.context_processors.request` to `TEMPLATE_CONTEXT_PROCESSORS` and make sure to use `RequestContext`. * This snippet overrides the existing `url` template tag. Remove the last line and register the new `url` function properly, as a separate tag, if this makes you unhappy. You'd then have to change your templates to use it. * It would be nicer to change the way reverse look-ups behave instead of changing only the `url` template tag, but the URL resolver, and the `reverse` function, know nothing about requests, so have no way to find the correct host name.
Allows url patterns to include a boolean indicating whether a view requires TLS(SSL). The accompanying middleware handles the redirects needed to make sure that it upholds this requirement. **WARNING**: this monkey-patches some Django internals and is difficult to test since Django's TestClient does not support TLS. If you use this make sure you test it thouroughly. Add this to your Django settings USE_TLS = True # The default for this setting is False. URL pattern usage url(r'^login$', 'myproject.login.index', {'require_tls': True}, name='login-index'), Use `require_tls` True to force the middleware to perform redirects needed to make sure your are serving this view using https. Use `require_tls` False to force the middleware to redirect to http. Be careful with this setting, this may not behave as you expect. If you don't care if the view is served via https or http then do not include `require_tls` in the pattern. If you wish to have every view in the site served with TLS then specify the following Django setting ALWAYS_USE_TLS = True # Django setting, use TLS for every view
This is a copy of [snippet 654](http://djangosnippets.org/snippets/654/), modified to allow dynamic MEDIA_URL, as you might need that for SSL in combination with [snippet 1754](http://djangosnippets.org/snippets/1754/). This is a template filter to enable the use of the MEDIA_URL setting in content from the flatpages database table. It searches for {{ MEDIA_URL }} and replaces it with the current MEDIA_URL added by a context processor. Note: To set up, drop the above code into a file called media_url.py in your templatetags directory in one of your INSTALLED_APPS, and add the filter to your flatpages template like so: {% load media_url %} {{ flatpage.content|media_url:MEDIA_URL }}
Add `FakeSSLMiddleware` to the top of your `MIDDLEWARE_CLASSES` stack when running tests or developing locally to allow https:// links to operate correctly. Can be used in conjunction with other SSL middleware to allow critical tests to be performed.
See docstrings for details. To use, add to `MIDDLEWARE_CLASSES` in `settings.py`, and in your `views.py`: 1. `from path.to.this.middleware import secure` 2. Decorate SSL views with `@secure`
This is a quick hack to address the SSL info leakage covered here: http://www.freedom-to-tinker.com/blog/felten/side-channel-leaks-web-applications Don't use this in prod without testing. :-) I'll get some feedback from django-dev and update here.
If you request static files such as images, javascript or css using http rather than https, the browser will complain that your site is not secure. This simple context processor will replace http:// with https:// in your MEDIA_URL if your static files are being included from an https page. In your settings.py just replace 'django.core.context_processors.media' with your new context processor.
On WebFaction, each host has it's own Apache instance, with WebFaction's main Apache instance forwarding requests. This is very useful but means that some of the original information is lost. This middleware should be installed at the top of your list to restore this lost info. It includes the functionality that used to be in SetRemoteAddrFromForwardedFor before it was removed from Django.
This snippet monkey-patches Django's reverse() method (use for generating URLs from vew functions and parameters) to allow certain areas of your site to automatically have URLs with the correct SSL domain in place. This saves you from having to use unnecessary redirects to guide users to an SSL-encrypted version of a page. This should still be used alongside a redirect-based method (such as [this snippet](http://www.djangosnippets.org/snippets/85/)) to ensure that the user can't access an unencrypted version of the page Simply add the code to the files mentioned in the code. This obviously won't work anywhere that doesn't use reverse(), the admin app seems to be an example of this.
Wrote this some time ago when I couldn't find one already completed. Came up in the IRC channel so I decided to post it. Easy enough to use. `from ssldecorator import ssl_required` `@ssl_required` `def your_view(request):` ` ''' your code here '''` You can place a variable in your settings.py to change the SSL domain (ie, if you have SSL running on secure.yourdomain.com instead of www.yourdomain.com).. `SSL_DOMAIN = 'https://secure.yourdomain.com'` Note: please include a proper URL. If https isn't used, the decorator will add it.
I had some trouble getting other peoples code to work for AD support, so I wrote my own which authenticates against LDAP and will also use SSL and cert if required. It will also verify that an autheticated user has specific group membership before authorizing. This will also debug to a file, which is really helpful when trying to figure out problems. One thing that really got me when getting python-ldap to work was that you must have "ldap.set_option(ldap.OPT_REFERRALS,0)" set or any ldap search will not work. Also, this will add group permissions to a user.
While we're on the topic of SSLRedirect (See snippet 240 and 880) here's what I add to the end of my ssl middleware module, so that SSLRedirect wont break my automated testing. It simply creates a dummy middleware class that removes the SSL argument, but does not do any redirecting. If you were to simply remove the middleware from settings, the extra SSL argument will then get passed on to all the relevant views. Of course, you'll need to define a TESTING variable in settings, or change this to something else like settings.DEBUG. Having the separate variable for testing allows you to run your server in DEBUG mode without side effects like the change above.
Snippet 240 is great, but it does not handle flatpages since flatpages are not technically a view. This operates on the request level, not the view level so it will handle flat pages. **Step 1** Add this class to your MIDDLEWARE_CLASSES **Step 2** Add an entry in settings.py which is a list of regex to match against urls that u want to have ssl: SSL_URLS = ( r'/login/', r'/home/', r'/super-sensitive-information/', )
*NOTE Stephen updated his original snippet http://www.djangosnippets.org/snippets/85/ to work with WebFaction, please use his version now* This code is 95% from Stephen Zabel's snippet at http://www.djangosnippets.org/snippets/85/. However, his snippet, as it was, wouldn't work when enabling SSL for the admin site on Webfaction. For some reason, the default request.is_secure() doesn't behave properly with Webfaction's setup and redirects. One thing Webfaction does do is add X-Forwarded-ssl='on' to any https requests. So instead of using request.is_secure(), I've just used that. To setup the admin site with SSL on Webfaction, do the following: 1. Install this middleware wherever you like, and add it to settings.py 2. In your Webfaction panel, create your 'django' application ("application" in the Webfaction sense, not the Django sense) 3. Create two sites. The first, your main site (which I'll call example.com), should use the application 'django' mounted at '/'. Do *not* have HTTPS enabled on this site. 4. For the second site, also use the application 'django', and again mount it to '/', but this time enable HTTPS. 5. In your urls.py, modify the admin URL as follows: `(r'^admin/', include('django.contrib.admin.urls'), {'SSL':True} )` That should be it! The admin section of the site now requires SSL (as specified in urls.py), and if anyone tries to access the admin via regular http, a redirect to https will occur.
16 snippets posted so far.