cundi / blog

push issues as a blog
2 stars 0 forks source link

django/1.8/topics/http/sessions/ #11

Open cundi opened 8 years ago

cundi commented 8 years ago

How to use sessions 如何使用会话

Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID – not the data itself (unless you’re using thecookie based backend).

Django对匿名会话是完全支持的。会话框架允许你存储并重新取回基本的站点单个访问用户的任意数据。会话将数据存储在服务器端,并且对发送和接收的cookies进行抽象。Cookies包含了一个会话ID——而不是session数据本身(除非你是在使用基于cookie的后端)。

Enabling sessions 启用会话

Sessions are implemented via a piece of middleware.

会话是通过一组中间件实现的。

To enable session functionality, do the following:

要启用会话功能,请按照以下操作执行:

Edit the MIDDLEWARE_CLASSES setting and make sure it contains 'django.contrib.sessions.middleware.SessionMiddleware'. The default settings.py created by django-admin startproject has SessionMiddleware activated. If you don’t want to use sessions, you might as well remove the SessionMiddleware line from MIDDLEWARE_CLASSES and 'django.contrib.sessions' from your INSTALLED_APPS. It’ll save you a small bit of overhead.


Configuring the session engine 配置会话引擎

By default, Django stores sessions in your database (using the model django.contrib.sessions.models.Session). Though this is convenient, in some setups it’s faster to store session data elsewhere, so Django can be configured to store session data on your filesystem or in your cache.

默认情况下,Django将会话存储在数据库中(使用的是模型是:django.contrib.sessions.models.Session)。尽管这样做比较方便,但是在某些设置中将会话数据存储到其他地方会更快一些,因此你可以透过配置Django讲会话数据存储到文件系统或者是缓存中。

Using database-backed sessions 使用支持数据库的会话

If you want to use a database-backed session, you need to add 'django.contrib.sessions' to your INSTALLED_APPS setting.

假如你想要使用支持数据库的会话,那么你需要添加 'django.contrib.sessions' 到项目的设置INSTALLED_APPS中。

Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.

在你配置好了要使用的应用之后,可以运行manage.py migrate以安装存储会话数据的单个数据库表。

Using cached sessions 使用基于缓存的会话

For better performance, you may want to use a cache-based session backend.

为了更高一些的性能考虑,你可以使用基于缓存的会话后端。

To store session data using Django’s cache system, you’ll first need to make sure you’ve configured your cache; see the cache documentation for details.

要使用Django的缓存系统来出处会话数据,首先你需要保证自己配置了缓存;详情参照文档的缓存部分。

Warning 警告⚠

You should only use cache-based sessions if you’re using the Memcached cache backend. The local-memory cache backend doesn’t retain data long enough to be a good choice, and it’ll be faster to use file or database sessions directly instead of sending everything through the file or database cache backends. Additionally, the local-memory cache backend is NOT multi-process safe, therefore probably not a good choice for production environments.

如果你正在使用的是Memcached缓存后端,那么你就只应该使用基于缓存的会话。本地的内存缓存对记住过长的数据来说不是一个好的选择,而使用直接地文件会话或者数据库会话会更快一些,而不是发送任何内容都通过文件缓存后端或者是数据库缓存后端。此外,本地的内存缓存后端在多进程方面是不安全的,因此选择本地内存缓存在生产环境中使用可能不是一个明智的选择。

If you have multiple caches defined in CACHES, Django will use the default cache. To use another cache, set SESSION_CACHE_ALIAS to the name of that cache.

假如你在CACHES中定义了多个缓存,则Django会使用默认的那个。要使用其他的缓存方案,

Once your cache is configured, you’ve got two choices for how to store data in the cache:

Set SESSION_ENGINE to "django.contrib.sessions.backends.cache" for a simple caching session store. Session data will be stored directly in your cache. However, session data may not be persistent: cached data can be evicted if the cache fills up or if the cache server is restarted.

For persistent, cached data, set SESSION_ENGINE to "django.contrib.sessions.backends.cached_db". This uses a write-through cache – every write to the cache will also be written to the database. Session reads only use the database if the data is not already in the cache.

Both session stores are quite fast, but the simple cache is faster because it disregards persistence. In most cases, the cached_db backend will be fast enough, but if you need that last bit of performance, and are willing to let session data be expunged from time to time, the cache backend is for you.

If you use the cached_db session backend, you also need to follow the configuration instructions for the using database-backed sessions.

Changed in Django 1.7:

Before version 1.7, the cached_db backend always used the default cache rather than the SESSION_CACHE_ALIAS.


Using file-based sessions

To use file-based sessions, set the SESSION_ENGINE setting to "django.contrib.sessions.backends.file".

You might also want to set the SESSION_FILE_PATH setting (which defaults to output from tempfile.gettempdir(), most likely /tmp) to control where Django stores session files. Be sure to check that your Web server has permissions to read and write to this location.


Using cookie-based sessions

To use cookies-based sessions, set the SESSION_ENGINE setting to "django.contrib.sessions.backends.signed_cookies". The session data will be stored using Django’s tools for cryptographic signing and the SECRET_KEY setting.

Note

It’s recommended to leave the SESSION_COOKIE_HTTPONLY setting on True to prevent access to the stored data from JavaScript.

Warning

If the SECRET_KEY is not kept secret and you are using the PickleSerializer, this can lead to arbitrary remote code execution.

An attacker in possession of the SECRET_KEY can not only generate falsified session data, which your site will trust, but also remotely execute arbitrary code, as the data is serialized using pickle.

If you use cookie-based sessions, pay extra care that your secret key is always kept completely secret, for any system which might be remotely accessible.

The session data is signed but not encrypted

When using the cookies backend the session data can be read by the client.

A MAC (Message Authentication Code) is used to protect the data against changes by the client, so that the session data will be invalidated when being tampered with. The same invalidation happens if the client storing the cookie (e.g. your user’s browser) can’t store all of the session cookie and drops data. Even though Django compresses the data, it’s still entirely possible to exceed the common limit of 4096 bytes per cookie.

No freshness guarantee

Note also that while the MAC can guarantee the authenticity of the data (that it was generated by your site, and not someone else), and the integrity of the data (that it is all there and correct), it cannot guarantee freshness i.e. that you are being sent back the last thing you sent to the client. This means that for some uses of session data, the cookie backend might open you up to replay attacks. Unlike other session backends which keep a server-side record of each session and invalidate it when a user logs out, cookie-based sessions are not invalidated when a user logs out. Thus if an attacker steals a user’s cookie, they can use that cookie to login as that user even if the user logs out. Cookies will only be detected as ‘stale’ if they are older than your SESSION_COOKIE_AGE.

Performance

Finally, the size of a cookie can have an impact on the speed of your site.

Using sessions in views

When SessionMiddleware is activated, each HttpRequest object – the first argument to any Django view function – will have a session attribute, which is a dictionary-like object.

You can read it and write to request.session at any point in your view. You can edit it multiple times.

class backends.base.SessionBase This is the base class for all session objects. It has the following standard dictionary methods:

__getitem__(key)
Example: fav_color = request.session['fav_color']

__setitem__(key, value)
Example: request.session['fav_color'] = 'blue'

__delitem__(key)
Example: del request.session['fav_color']. This raises KeyError if the given key isn’t already in the session.

__contains__(key)
Example: 'fav_color' in request.session

get(key, default=None)
Example: fav_color = request.session.get('fav_color', 'red')

pop(key)
Example: fav_color = request.session.pop('fav_color')

keys()

items()

setdefault()

clear()

It also has these methods:

flush()
Deletes the current session data from the session and deletes the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser (for example, the django.contrib.auth.logout() function calls it).

Changed in Django 1.8:

Deletion of the session cookie is a behavior new in Django 1.8. Previously, the behavior was to regenerate the session key value that was sent back to the user in the cookie.

set_test_cookie()
Sets a test cookie to determine whether the user’s browser supports cookies. Due to the way cookies work, you won’t be able to test this until the user’s next page request. See Setting test cookies below for more information.

test_cookie_worked()
Returns either True or False, depending on whether the user’s browser accepted the test cookie. Due to the way cookies work, you’ll have to call set_test_cookie() on a previous, separate page request. See Setting test cookies below for more information.

delete_test_cookie()
Deletes the test cookie. Use this to clean up after yourself.

set_expiry(value) Sets the expiration time for the session. You can pass a number of different values:

Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was modified.

get_expiry_age()
Returns the number of seconds until this session expires. For sessions with no custom expiration (or those set to expire at browser close), this will equal SESSION_COOKIE_AGE.

This function accepts two optional keyword arguments:

get_expiry_date()
Returns the date this session will expire. For sessions with no custom expiration (or those set to expire at browser close), this will equal the date SESSION_COOKIE_AGE seconds from now.

This function accepts the same keyword arguments as get_expiry_age().

get_expire_at_browser_close()
Returns either True or False, depending on whether the user’s session cookie will expire when the user’s Web browser is closed.

clear_expired()
Removes expired sessions from the session store. This class method is called by clearsessions.

cycle_key()
Creates a new session key while retaining the current session data. django.contrib.auth.login() calls this method to mitigate against session fixation.

Session serialization

Before version 1.6, Django defaulted to using pickle to serialize session data before storing it in the backend. If you’re using the signed cookie session backend and SECRET_KEY is known by an attacker (there isn’t an inherent vulnerability in Django that would cause it to leak), the attacker could insert a string into their session which, when unpickled, executes arbitrary code on the server. The technique for doing so is simple and easily available on the internet. Although the cookie session storage signs the cookie-stored data to prevent tampering, a SECRET_KEY leak immediately escalates to a remote code execution vulnerability.

This attack can be mitigated by serializing session data using JSON rather than pickle. To facilitate this, Django 1.5.3 introduced a new setting, SESSION_SERIALIZER, to customize the session serialization format. For backwards compatibility, this setting defaults to using django.contrib.sessions.serializers.PickleSerializer in Django 1.5.x, but, for security hardening, defaults to django.contrib.sessions.serializers.JSONSerializer in Django 1.6. Even with the caveats described in Write Your Own Serializer, we highly recommend sticking with JSON serialization especially if you are using the cookie backend.

Bundled Serializers

class serializers.JSONSerializer A wrapper around the JSON serializer from django.core.signing. Can only serialize basic data types.

In addition, as JSON supports only string keys, note that using non-string keys in request.session won’t work as expected:

>>> # initial assignment
>>> request.session[0] = 'bar'
>>> # subsequent requests following serialization & deserialization
>>> # of session data
>>> request.session[0]  # KeyError
>>> request.session['0']
'bar'

See the Write Your Own Serializer section for more details on limitations of JSON serialization.

class serializers.PickleSerializer
Supports arbitrary Python objects, but, as described above, can lead to a remote code execution vulnerability if SECRET_KEY becomes known by an attacker.


Write Your Own Serializer

Note that unlike PickleSerializer, the JSONSerializer cannot handle arbitrary Python data types. As is often the case, there is a trade-off between convenience and security. If you wish to store more advanced data types including datetime and Decimal in JSON backed sessions, you will need to write a custom serializer (or convert such values to a JSON serializable object before storing them in request.session). While serializing these values is fairly straightforward (django.core.serializers.json.DateTimeAwareJSONEncoder may be helpful), writing a decoder that can reliably get back the same thing that you put in is more fragile. For example, you run the risk of returning a datetime that was actually a string that just happened to be in the same format chosen for datetimes).

Your serializer class must implement two methods, dumps(self, obj) and loads(self, data), to serialize and deserialize the dictionary of session data, respectively.


Session object guidelines


Examples 例子

This simplistic view sets a has_commented variable to True after a user posts a comment. It doesn’t let a user post a comment more than once:

下面这个非常简单的视图在用户发表了评论之后将has_commented变量设置为True。这样做可以让用户不会发表评论一次之后重复发表:

def post_comment(request, new_comment):
    if request.session.get('has_commented', False):
        return HttpResponse("You've already commented.")
    c = comments.Comment(comment=new_comment)
    c.save()
    request.session['has_commented'] = True
    return HttpResponse('Thanks for your comment!')

This simplistic view logs in a “member” of the site:

下面的这个简单的视图记录了当前站点的“成员”:

def login(request):
    m = Member.objects.get(username=request.POST['username'])
    if m.password == request.POST['password']:
        request.session['member_id'] = m.id
        return HttpResponse("You're logged in.")
    else:
        return HttpResponse("Your username and password didn't match.")

...And this one logs a member out, according to login() above:

def logout(request):
    try:
        del request.session['member_id']
    except KeyError:
        pass
    return HttpResponse("You're logged out.")

The standard django.contrib.auth.logout() function actually does a bit more than this to prevent inadvertent data leakage. It calls the flush() method of request.session. We are using this example as a demonstration of how to work with session objects, not as a full logout() implementation.


Setting test cookies 设置测试cookies

As a convenience, Django provides an easy way to test whether the user’s browser accepts cookies. Just call the set_test_cookie() method of request.session in a view, and call test_cookie_worked() in a subsequent view – not in the same view call.

为了方便开发者,Django提供了一种简单的方法来测试用户的浏览器是否接受cookies。你所需要做的就是,在视图中的调用request.session的set_test_cookie()方法,然后随后的视图(这里并不是在相同的视图中)中调用test_cookie_worked()。

This awkward split between set_test_cookie() and test_cookie_worked() is necessary due to the way cookies work. When you set a cookie, you can’t actually tell whether a browser accepted it until the browser’s next request.

It’s good practice to use delete_test_cookie() to clean up after yourself. Do this after you’ve verified that the test cookie worked.

最佳实践是你自己在稍后删除delete_test_cookie()。在你验证过测试cookie可以工作之后,在执行这个动作。

Here’s a typical usage example:

下面是一个典型的使用案例:

def login(request):
    if request.method == 'POST':
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
            return HttpResponse("You're logged in.")
        else:
            return HttpResponse("Please enable cookies and try again.")
    request.session.set_test_cookie()
    return render_to_response('foo/login_form.html')

Using sessions out of views 在视图之外使用session

Note注释

The examples in this section import the SessionStore object directly from the django.contrib.sessions.backends.db backend. In your own code, you should consider importing SessionStore from the session engine designated by SESSION_ENGINE, as below:

本节的这个例子直接从django.contrib.sessions.backends.db中导入了SessionStore对象。如下,在你自己的代码中,你应该考虑从指定的会话引擎SESSION_ENGINE中导入SessionStore

>> from importlib import import_module
>> from django.conf import settings
>> SessionStore = import_module(settings.SESSION_ENGINE).SessionStore

An API is available to manipulate session data outside of a view:

这里给你提供了一个可用的API,它可以在视图外部操作会话数据:

>>> from django.contrib.sessions.backends.db import SessionStore
>>> s = SessionStore()
>>> # stored as seconds since epoch since datetimes are not serializable in JSON.
>>> s['last_login'] = 1376587691
>>> s.save()
>>> s.session_key
'2b1189a188b44ad18c35e113ac6ceead'

>>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
>>> s['last_login']
1376587691

In order to mitigate session fixation attacks, sessions keys that don’t exist are regenerated:

>>> from django.contrib.sessions.backends.db import SessionStore
>>> s = SessionStore(session_key='no-such-session-here')
>>> s.save()
>>> s.session_key
'ff882814010ccbc3c870523934fee5a2'

If you’re using the django.contrib.sessions.backends.db backend, each session is just a normal Django model. The Session model is defined in django/contrib/sessions/models.py. Because it’s a normal model, you can access sessions using the normal Django database API:

>>> from django.contrib.sessions.models import Session
>>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
>>> s.expire_date
datetime.datetime(2005, 8, 20, 13, 35, 12)

Note that you’ll need to call get_decoded() to get the session dictionary. This is necessary because the dictionary is stored in an encoded format:

>>> s.session_data
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
>>> s.get_decoded()
{'user_id': 42}

When sessions are saved

By default, Django only saves to the session database when the session has been modified – that is if any of its dictionary values have been assigned or deleted:

# Session is modified.
request.session['foo'] = 'bar'

# Session is modified.
del request.session['foo']

# Session is modified.
request.session['foo'] = {}

# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session.
request.session['foo']['bar'] = 'baz'

In the last case of the above example, we can tell the session object explicitly that it has been modified by setting the modified attribute on the session object:

request.session.modified = True

To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST setting to True. When set to True, Django will save the session to the database on every single request.

Note that the session cookie is only sent when a session has been created or modified. If SESSION_SAVE_EVERY_REQUEST is True, the session cookie will be sent on every request.

Similarly, the expires part of a session cookie is updated each time the session cookie is sent.

The session is not saved if the response’s status code is 500.


Browser-length sessions vs. persistent sessions

You can control whether the session framework uses browser-length sessions vs. persistent sessions with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting.

By default, SESSION_EXPIRE_AT_BROWSER_CLOSE is set to False, which means session cookies will be stored in users’ browsers for as long as SESSION_COOKIE_AGE. Use this if you don’t want people to have to log in every time they open a browser.

If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django will use browser-length cookies – cookies that expire as soon as the user closes their browser. Use this if you want people to have to log in every time they open a browser.

This setting is a global default and can be overwritten at a per-session level by explicitly calling the set_expiry() method of request.session as described above in using sessions in views.

Note

Some browsers (Chrome, for example) provide settings that allow users to continue browsing sessions after closing and re-opening the browser. In some cases, this can interfere with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting and prevent sessions from expiring on browser close. Please be aware of this while testing Django applications which have the SESSION_EXPIRE_AT_BROWSER_CLOSE setting enabled.


Clearing the session store

As users create new sessions on your website, session data can accumulate in your session store. If you’re using the database backend, the django_session database table will grow. If you’re using the file backend, your temporary directory will contain an increasing number of files.

To understand this problem, consider what happens with the database backend. When a user logs in, Django adds a row to the django_session database table. Django updates this row each time the session data changes. If the user logs out manually, Django deletes the row. But if the user does not log out, the row never gets deleted. A similar process happens with the file backend.

Django does not provide automatic purging of expired sessions. Therefore, it’s your job to purge expired sessions on a regular basis. Django provides a clean-up management command for this purpose: clearsessions. It’s recommended to call this command on a regular basis, for example as a daily cron job.

Note that the cache backend isn’t vulnerable to this problem, because caches automatically delete stale data. Neither is the cookie backend, because the session data is stored by the users’ browsers.


Settings

A few Django settings give you control over session behavior:

SESSION_CACHE_ALIAS SESSION_COOKIE_AGE SESSION_COOKIE_DOMAIN SESSION_COOKIE_HTTPONLY SESSION_COOKIE_NAME SESSION_COOKIE_PATH SESSION_COOKIE_SECURE SESSION_ENGINE SESSION_EXPIRE_AT_BROWSER_CLOSE SESSION_FILE_PATH SESSION_SAVE_EVERY_REQUEST


Session security

Subdomains within a site are able to set cookies on the client for the whole domain. This makes session fixation possible if cookies are permitted from subdomains not controlled by trusted users.

For example, an attacker could log into good.example.com and get a valid session for their account. If the attacker has control over bad.example.com, they can use it to send their session key to you since a subdomain is permitted to set cookies on *.example.com. When you visit good.example.com, you’ll be logged in as the attacker and might inadvertently enter your sensitive personal data (e.g. credit card info) into the attackers account.

Another possible attack would be if good.example.com sets its SESSION_COOKIE_DOMAIN to ".example.com" which would cause session cookies from that site to be sent to bad.example.com.


Technical details


Session IDs in URLs URL中的SessionID

The Django sessions framework is entirely, and solely, cookie-based. It does not fall back to putting session IDs in URLs as a last resort, as PHP does. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the “Referer” header.

Django的Session是基于cookies的独立地、完整地框架。它不像PHP那样在URL中回滚最新的session ID。这是一种国际化的设计决策的后果。PHP不仅让你的URL变的丑陋,而且会通过“Referer”首部盗用回话ID使你的网站变的很脆弱。