| | 1 | ============== |
|---|
| | 2 | Signed cookies |
|---|
| | 3 | ============== |
|---|
| | 4 | |
|---|
| | 5 | While cookies are a convenient way to store basic persistent data in client |
|---|
| | 6 | browsers, users are free to edit them at will, making them inherently insecure. |
|---|
| | 7 | By attaching signatures to cookies, you can confidently trust that their values |
|---|
| | 8 | are safe from editing. |
|---|
| | 9 | |
|---|
| | 10 | How it works |
|---|
| | 11 | ============ |
|---|
| | 12 | |
|---|
| | 13 | Cookies are signed by attaching a digest to the cookie value that can be |
|---|
| | 14 | verified when the cookie is sent back to the server. This digest is created from |
|---|
| | 15 | the cookie's name and value, along with the site's secret_. |
|---|
| | 16 | |
|---|
| | 17 | Essentially, this creates a set of four values that must all remain intact in |
|---|
| | 18 | order for the cookie to validate properly. If any one of these is altered on a |
|---|
| | 19 | client computer, the cookie will be invalid. |
|---|
| | 20 | |
|---|
| | 21 | * ``settings.SECRET_KEY`` |
|---|
| | 22 | * Name |
|---|
| | 23 | * Value |
|---|
| | 24 | * Signature |
|---|
| | 25 | |
|---|
| | 26 | This set of values ensures that users are unable to rename the cookie or edit |
|---|
| | 27 | its value without generating a new signature. Since the secret is known |
|---|
| | 28 | only to site administrators, users will be unable to generate signatures that |
|---|
| | 29 | will validate with altered values. |
|---|
| | 30 | |
|---|
| | 31 | .. _secret: ../settings/#secret-key |
|---|
| | 32 | |
|---|
| | 33 | Automatic signing |
|---|
| | 34 | ================= |
|---|
| | 35 | |
|---|
| | 36 | The easiest and most reliable way to sign your cookies is to use the provided |
|---|
| | 37 | middleware, which will automatically handle everything behind the scenes. In |
|---|
| | 38 | fact, aside from a single line in your settings, using the middleware requires |
|---|
| | 39 | no changes in your code. |
|---|
| | 40 | |
|---|
| | 41 | Activating the middleware |
|---|
| | 42 | ------------------------- |
|---|
| | 43 | |
|---|
| | 44 | Simply add a ``'SignedCookiesMiddleware'`` reference to your |
|---|
| | 45 | ``MIDDLEWARE_CLASSES`` setting to enjoy signature protection for all your views. |
|---|
| | 46 | One thing to keep in mind is that, while all views are automatically handled, |
|---|
| | 47 | middleware will only be protected if they are positioned *after* signed cookies. |
|---|
| | 48 | |
|---|
| | 49 | Invalid cookies |
|---|
| | 50 | --------------- |
|---|
| | 51 | |
|---|
| | 52 | Signing and validation are both handled transparently to views, with invalid |
|---|
| | 53 | cookies being silently removed from ``request.COOKIES`` prior to executing the |
|---|
| | 54 | view. This means that views will see no difference between an unsigned cookie |
|---|
| | 55 | and no cookie at all. |
|---|
| | 56 | |
|---|
| | 57 | As with a missing cookie, a proper cookie can simply be set within the view, |
|---|
| | 58 | which will then be signed properly and will validate on the next request. |
|---|
| | 59 | |
|---|
| | 60 | A note about sessions |
|---|
| | 61 | --------------------- |
|---|
| | 62 | |
|---|
| | 63 | Though the `sessions framework`_ uses cookies, it only stores the ID, which is |
|---|
| | 64 | considered safe. This means that it can safely be placed before signed cookies |
|---|
| | 65 | in your ``MIDDLEWARE_CLASSES``. |
|---|
| | 66 | |
|---|
| | 67 | .. _sessions framework: ../sessions/ |
|---|
| | 68 | |
|---|
| | 69 | Example |
|---|
| | 70 | ------- |
|---|
| | 71 | |
|---|
| | 72 | This is an example of how ``MIDDLEWARE_CLASSES`` might look. |
|---|
| | 73 | |
|---|
| | 74 | MIDDLEWARE_CLASSES = ( |
|---|
| | 75 | 'django.middleware.common.CommonMiddleware', |
|---|
| | 76 | 'django.contrib.sessions.middleware.SessionMiddleware', |
|---|
| | 77 | 'django.contrib.signedcookies.middleware.SignedCookiesMiddleware', |
|---|
| | 78 | 'django.contrib.auth.middleware.AuthenticationMiddleware', |
|---|
| | 79 | 'django.middleware.doc.XViewMiddleware', |
|---|
| | 80 | ) |
|---|
| | 81 | |
|---|
| | 82 | Manual signing |
|---|
| | 83 | ============== |
|---|
| | 84 | |
|---|
| | 85 | If only a portion of the project needs signed cookies, there is a manual option |
|---|
| | 86 | that doesn't rely on middleware. There are two functions provided, which can be |
|---|
| | 87 | used to manually sign and validate cookie values within views. |
|---|
| | 88 | |
|---|
| | 89 | These utilities live in ``django.contrib.signedcookies.utils``. |
|---|
| | 90 | |
|---|
| | 91 | sign(key, unsigned_value) |
|---|
| | 92 | ------------------------- |
|---|
| | 93 | |
|---|
| | 94 | When setting cookies, a signature can be attached manually by using this simple |
|---|
| | 95 | function. It takes the cookie's name and value and returns a signed value that |
|---|
| | 96 | is suitable for being set to a cookie. |
|---|
| | 97 | |
|---|
| | 98 | This function will not set the cookie to the response; this still has to be done |
|---|
| | 99 | according to HttpResponse_. |
|---|
| | 100 | |
|---|
| | 101 | .. _HttpResponse: ../request_response/ |
|---|
| | 102 | |
|---|
| | 103 | unsign(key, signed_value) |
|---|
| | 104 | ------------------------- |
|---|
| | 105 | |
|---|
| | 106 | When receiving a signed cookie from an incoming request, the signature will |
|---|
| | 107 | still be attached, and must be manually validated and removed using this |
|---|
| | 108 | function. This single function handles both tasks, raising an error for invalid |
|---|
| | 109 | or unsigned cookies, and returning the plain, unsigned value when successful. |
|---|
| | 110 | |
|---|
| | 111 | Invalid cookies |
|---|
| | 112 | --------------- |
|---|
| | 113 | |
|---|
| | 114 | If the cookie is not signed or invalid, ``unsign`` will raise an exception, |
|---|
| | 115 | which must be handled by the view to prevent server error responses. There are |
|---|
| | 116 | multiple exception types that could be thrown, so a simple ``except`` would be |
|---|
| | 117 | appropriate. |
|---|
| | 118 | |
|---|
| | 119 | As shown in the example below, a single try/except block is suitable for |
|---|
| | 120 | handling errors due to a missing, unsigned or invalid cookie. |
|---|
| | 121 | |
|---|
| | 122 | Example |
|---|
| | 123 | ------- |
|---|
| | 124 | |
|---|
| | 125 | The following example assumes you have some shopping cart data that can be |
|---|
| | 126 | stored in a cookie, and will be used to populate some ``ShoppingCart`` object. |
|---|
| | 127 | |
|---|
| | 128 | from django.http import HttpResponse |
|---|
| | 129 | from django.contrib.signedcookies import utils |
|---|
| | 130 | from myapp.utils import ShoppingCart |
|---|
| | 131 | |
|---|
| | 132 | def view_cart(request): |
|---|
| | 133 | response = HttpResponse() |
|---|
| | 134 | try: |
|---|
| | 135 | cart = ShoppingCart(utils.unsign('cart', request.COOKIES['cart'])) |
|---|
| | 136 | except: |
|---|
| | 137 | # The cookie was no good, so a new one should be set |
|---|
| | 138 | cart = ShoppingCart() |
|---|
| | 139 | response.set_cookie('cart', utils.sign('cart', cart.cookie_data)) |
|---|
| | 140 | |
|---|
| | 141 | # Continue processing the shopping cart |
|---|
| | 142 | |
|---|
| | 143 | return respose |
|---|
| | 144 | |
|---|
| | 145 | A note about stolen cookies |
|---|
| | 146 | =========================== |
|---|
| | 147 | |
|---|
| | 148 | While cookie signing is a reasonable way to ensure that a cookie has not been |
|---|
| | 149 | edited, there is no guarantee that it is being requested by the same computer |
|---|
| | 150 | where it was first set. If a computer is compromised and its cookies stolen, |
|---|
| | 151 | the thief would be able to use the signed cookie with no interference. |
|---|
| | 152 | |
|---|
| | 153 | Therefore, any applications that implement mission-critical functionality with |
|---|
| | 154 | signed cookies should take extra precautions to anticipate cookie theft. |