mirror of
https://github.com/django/django.git
synced 2025-03-22 23:30:45 +00:00
Fixed #19498 -- refactored auth documentation
The auth doc was a single page which had grown unwieldy. This refactor split and grouped the content into sub-topics. Additional corrections and cleanups were made along the way.
This commit is contained in:
parent
db278c3bf9
commit
11ded967c4
@ -4,7 +4,7 @@ Authenticating against Django's user database from Apache
|
||||
|
||||
Since keeping multiple authentication databases in sync is a common problem when
|
||||
dealing with Apache, you can configure Apache to authenticate against Django's
|
||||
:doc:`authentication system </topics/auth>` directly. This requires Apache
|
||||
:doc:`authentication system </topics/auth/index>` directly. This requires Apache
|
||||
version >= 2.2 and mod_wsgi >= 2.0. For example, you could:
|
||||
|
||||
* Serve static/media files directly from Apache only to authenticated users.
|
||||
|
@ -246,7 +246,7 @@ Common Web application tools
|
||||
Django offers multiple tools commonly needed in the development of Web
|
||||
applications:
|
||||
|
||||
* :doc:`Authentication <topics/auth>`
|
||||
* :doc:`Authentication <topics/auth/index>`
|
||||
* :doc:`Caching <topics/cache>`
|
||||
* :doc:`Logging <topics/logging>`
|
||||
* :doc:`Sending emails <topics/email>`
|
||||
|
@ -134,7 +134,7 @@ part of Django itself, and so are no longer separately maintained:
|
||||
of Django since the 0.95 release.
|
||||
|
||||
* ``multi-auth``: A refactoring of :doc:`Django's bundled
|
||||
authentication framework </topics/auth>` which added support for
|
||||
authentication framework </topics/auth/index>` which added support for
|
||||
:ref:`authentication backends <authentication-backends>`. This has
|
||||
been part of Django since the 0.95 release.
|
||||
|
||||
|
@ -38,7 +38,7 @@ In general, everything covered in the documentation -- with the exception of
|
||||
anything in the :doc:`internals area </internals/index>` is considered stable as
|
||||
of 1.0. This includes these APIs:
|
||||
|
||||
- :doc:`Authorization </topics/auth>`
|
||||
- :doc:`Authorization </topics/auth/index>`
|
||||
|
||||
- :doc:`Caching </topics/cache>`.
|
||||
|
||||
|
@ -1,33 +0,0 @@
|
||||
=======================
|
||||
Authentication backends
|
||||
=======================
|
||||
|
||||
.. module:: django.contrib.auth.backends
|
||||
:synopsis: Django's built-in authentication backend classes.
|
||||
|
||||
This document details the authentication backends that come with Django. For
|
||||
information on how to use them and how to write your own authentication
|
||||
backends, see the :ref:`Other authentication sources section
|
||||
<authentication-backends>` of the :doc:`User authentication guide
|
||||
</topics/auth>`.
|
||||
|
||||
|
||||
Available authentication backends
|
||||
=================================
|
||||
|
||||
The following backends are available in :mod:`django.contrib.auth.backends`:
|
||||
|
||||
.. class:: ModelBackend
|
||||
|
||||
This is the default authentication backend used by Django. It
|
||||
authenticates using usernames and passwords stored in the
|
||||
:class:`~django.contrib.auth.models.User` model.
|
||||
|
||||
|
||||
.. class:: RemoteUserBackend
|
||||
|
||||
Use this backend to take advantage of external-to-Django-handled
|
||||
authentication. It authenticates using usernames passed in
|
||||
:attr:`request.META['REMOTE_USER'] <django.http.HttpRequest.META>`. See
|
||||
the :doc:`Authenticating against REMOTE_USER </howto/auth-remote-user>`
|
||||
documentation.
|
@ -1,4 +1,430 @@
|
||||
``django.contrib.auth``
|
||||
=======================
|
||||
|
||||
See :doc:`/topics/auth`.
|
||||
This document provides API reference material for the components of Django's
|
||||
authentication system. For more details on the usage of these components or
|
||||
how to customize authentication and authorization see the :doc:`authentication
|
||||
topic guide </topics/auth/index>`.
|
||||
|
||||
.. currentmodule:: django.contrib.auth
|
||||
|
||||
User
|
||||
====
|
||||
|
||||
Fields
|
||||
------
|
||||
|
||||
.. class:: models.User
|
||||
|
||||
:class:`~django.contrib.auth.models.User` objects have the following
|
||||
fields:
|
||||
|
||||
.. attribute:: username
|
||||
|
||||
Required. 30 characters or fewer. Usernames may contain alphanumeric,
|
||||
``_``, ``@``, ``+``, ``.`` and ``-`` characters.
|
||||
|
||||
.. attribute:: first_name
|
||||
|
||||
Optional. 30 characters or fewer.
|
||||
|
||||
.. attribute:: last_name
|
||||
|
||||
Optional. 30 characters or fewer.
|
||||
|
||||
.. attribute:: email
|
||||
|
||||
Optional. Email address.
|
||||
|
||||
.. attribute:: password
|
||||
|
||||
Required. A hash of, and metadata about, the password. (Django doesn't
|
||||
store the raw password.) Raw passwords can be arbitrarily long and can
|
||||
contain any character. See the :doc:`password documentation
|
||||
</topics/auth/passwords>`.
|
||||
|
||||
.. attribute:: groups
|
||||
|
||||
Many-to-many relationship to :class:`~django.contrib.auth.models.Group`
|
||||
|
||||
.. attribute:: user_permissions
|
||||
|
||||
Many-to-many relationship to :class:`~django.contrib.auth.models.Permission`
|
||||
|
||||
.. attribute:: is_staff
|
||||
|
||||
Boolean. Designates whether this user can access the admin site.
|
||||
|
||||
.. attribute:: is_active
|
||||
|
||||
Boolean. Designates whether this user account should be considered
|
||||
active. We recommend that you set this flag to ``False`` instead of
|
||||
deleting accounts; that way, if your applications have any foreign keys
|
||||
to users, the foreign keys won't break.
|
||||
|
||||
This doesn't necessarily control whether or not the user can log in.
|
||||
Authentication backends aren't required to check for the ``is_active``
|
||||
flag, and the default backends do not. If you want to reject a login
|
||||
based on ``is_active`` being ``False``, it's up to you to check that in
|
||||
your own login view or a custom authentication backend. However, the
|
||||
:class:`~django.contrib.auth.forms.AuthenticationForm` used by the
|
||||
:func:`~django.contrib.auth.views.login` view (which is the default)
|
||||
*does* perform this check, as do the permission-checking methods such
|
||||
as :meth:`~django.contrib.auth.models.User.has_perm` and the
|
||||
authentication in the Django admin. All of those functions/methods will
|
||||
return ``False`` for inactive users.
|
||||
|
||||
.. attribute:: is_superuser
|
||||
|
||||
Boolean. Designates that this user has all permissions without
|
||||
explicitly assigning them.
|
||||
|
||||
.. attribute:: last_login
|
||||
|
||||
A datetime of the user's last login. Is set to the current date/time by
|
||||
default.
|
||||
|
||||
.. attribute:: date_joined
|
||||
|
||||
A datetime designating when the account was created. Is set to the
|
||||
current date/time by default when the account is created.
|
||||
|
||||
Methods
|
||||
-------
|
||||
|
||||
.. class:: models.User
|
||||
|
||||
.. method:: get_username()
|
||||
|
||||
Returns the username for the user. Since the User model can be swapped
|
||||
out, you should use this method instead of referencing the username
|
||||
attribute directly.
|
||||
|
||||
.. method:: is_anonymous()
|
||||
|
||||
Always returns ``False``. This is a way of differentiating
|
||||
:class:`~django.contrib.auth.models.User` and
|
||||
:class:`~django.contrib.auth.models.AnonymousUser` objects.
|
||||
Generally, you should prefer using
|
||||
:meth:`~django.contrib.auth.models.User.is_authenticated()` to this
|
||||
method.
|
||||
|
||||
.. method:: is_authenticated()
|
||||
|
||||
Always returns ``True``. This is a way to tell if the user has been
|
||||
authenticated. This does not imply any permissions, and doesn't check
|
||||
if the user is active - it only indicates that the user has provided a
|
||||
valid username and password.
|
||||
|
||||
.. method:: get_full_name()
|
||||
|
||||
Returns the :attr:`~django.contrib.auth.models.User.first_name` plus
|
||||
the :attr:`~django.contrib.auth.models.User.last_name`, with a space in
|
||||
between.
|
||||
|
||||
.. method:: set_password(raw_password)
|
||||
|
||||
Sets the user's password to the given raw string, taking care of the
|
||||
password hashing. Doesn't save the
|
||||
:class:`~django.contrib.auth.models.User` object.
|
||||
|
||||
.. method:: check_password(raw_password)
|
||||
|
||||
Returns ``True`` if the given raw string is the correct password for
|
||||
the user. (This takes care of the password hashing in making the
|
||||
comparison.)
|
||||
|
||||
.. method:: set_unusable_password()
|
||||
|
||||
Marks the user as having no password set. This isn't the same as
|
||||
having a blank string for a password.
|
||||
:meth:`~django.contrib.auth.models.User.check_password()` for this user
|
||||
will never return ``True``. Doesn't save the
|
||||
:class:`~django.contrib.auth.models.User` object.
|
||||
|
||||
You may need this if authentication for your application takes place
|
||||
against an existing external source such as an LDAP directory.
|
||||
|
||||
.. method:: has_usable_password()
|
||||
|
||||
Returns ``False`` if
|
||||
:meth:`~django.contrib.auth.models.User.set_unusable_password()` has
|
||||
been called for this user.
|
||||
|
||||
.. method:: get_group_permissions(obj=None)
|
||||
|
||||
Returns a set of permission strings that the user has, through his/her
|
||||
groups.
|
||||
|
||||
If ``obj`` is passed in, only returns the group permissions for
|
||||
this specific object.
|
||||
|
||||
.. method:: get_all_permissions(obj=None)
|
||||
|
||||
Returns a set of permission strings that the user has, both through
|
||||
group and user permissions.
|
||||
|
||||
If ``obj`` is passed in, only returns the permissions for this
|
||||
specific object.
|
||||
|
||||
.. method:: has_perm(perm, obj=None)
|
||||
|
||||
Returns ``True`` if the user has the specified permission, where perm
|
||||
is in the format ``"<app label>.<permission codename>"``. (see
|
||||
documentation on :ref:`permissions <topic-authorization>`). If the user is
|
||||
inactive, this method will always return ``False``.
|
||||
|
||||
If ``obj`` is passed in, this method won't check for a permission for
|
||||
the model, but for this specific object.
|
||||
|
||||
.. method:: has_perms(perm_list, obj=None)
|
||||
|
||||
Returns ``True`` if the user has each of the specified permissions,
|
||||
where each perm is in the format
|
||||
``"<app label>.<permission codename>"``. If the user is inactive,
|
||||
this method will always return ``False``.
|
||||
|
||||
If ``obj`` is passed in, this method won't check for permissions for
|
||||
the model, but for the specific object.
|
||||
|
||||
.. method:: has_module_perms(package_name)
|
||||
|
||||
Returns ``True`` if the user has any permissions in the given package
|
||||
(the Django app label). If the user is inactive, this method will
|
||||
always return ``False``.
|
||||
|
||||
.. method:: email_user(subject, message, from_email=None)
|
||||
|
||||
Sends an email to the user. If ``from_email`` is ``None``, Django uses
|
||||
the :setting:`DEFAULT_FROM_EMAIL`.
|
||||
|
||||
.. method:: get_profile()
|
||||
|
||||
.. deprecated:: 1.5
|
||||
With the introduction of :ref:`custom User models <auth-custom-user>`,
|
||||
the use of :setting:`AUTH_PROFILE_MODULE` to define a single profile
|
||||
model is no longer supported. See the
|
||||
:doc:`Django 1.5 release notes</releases/1.5>` for more information.
|
||||
|
||||
Returns a site-specific profile for this user. Raises
|
||||
``django.contrib.auth.models.SiteProfileNotAvailable`` if the
|
||||
current site doesn't allow profiles, or
|
||||
:exc:`django.core.exceptions.ObjectDoesNotExist` if the user does not
|
||||
have a profile.
|
||||
|
||||
Manager methods
|
||||
---------------
|
||||
|
||||
.. class:: models.UserManager
|
||||
|
||||
The :class:`~django.contrib.auth.models.User` model has a custom manager
|
||||
that has the following helper methods:
|
||||
|
||||
.. method:: create_user(username, email=None, password=None)
|
||||
|
||||
.. versionchanged:: 1.4
|
||||
The ``email`` parameter was made optional. The username
|
||||
parameter is now checked for emptiness and raises a
|
||||
:exc:`~exceptions.ValueError` in case of a negative result.
|
||||
|
||||
Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
|
||||
|
||||
The :attr:`~django.contrib.auth.models.User.username` and
|
||||
:attr:`~django.contrib.auth.models.User.password` are set as given. The
|
||||
domain portion of :attr:`~django.contrib.auth.models.User.email` is
|
||||
automatically converted to lowercase, and the returned
|
||||
:class:`~django.contrib.auth.models.User` object will have
|
||||
:attr:`~django.contrib.auth.models.User.is_active` set to ``True``.
|
||||
|
||||
If no password is provided,
|
||||
:meth:`~django.contrib.auth.models.User.set_unusable_password()` will
|
||||
be called.
|
||||
|
||||
See :ref:`Creating users <topics-auth-creating-users>` for example usage.
|
||||
|
||||
.. method:: make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
|
||||
|
||||
Returns a random password with the given length and given string of
|
||||
allowed characters. (Note that the default value of ``allowed_chars``
|
||||
doesn't contain letters that can cause user confusion, including:
|
||||
|
||||
* ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
|
||||
letter L, uppercase letter i, and the number one)
|
||||
* ``o``, ``O``, and ``0`` (uppercase letter o, lowercase letter o,
|
||||
and zero)
|
||||
|
||||
|
||||
Anonymous users
|
||||
===============
|
||||
|
||||
.. class:: models.AnonymousUser
|
||||
|
||||
:class:`django.contrib.auth.models.AnonymousUser` is a class that
|
||||
implements the :class:`django.contrib.auth.models.User` interface, with
|
||||
these differences:
|
||||
|
||||
* :ref:`id <automatic-primary-key-fields>` is always ``None``.
|
||||
* :attr:`~django.contrib.auth.models.User.is_staff` and
|
||||
:attr:`~django.contrib.auth.models.User.is_superuser` are always
|
||||
``False``.
|
||||
* :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
|
||||
* :attr:`~django.contrib.auth.models.User.groups` and
|
||||
:attr:`~django.contrib.auth.models.User.user_permissions` are always
|
||||
empty.
|
||||
* :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True``
|
||||
instead of ``False``.
|
||||
* :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
|
||||
``False`` instead of ``True``.
|
||||
* :meth:`~django.contrib.auth.models.User.set_password()`,
|
||||
:meth:`~django.contrib.auth.models.User.check_password()`,
|
||||
:meth:`~django.db.models.Model.save` and
|
||||
:meth:`~django.db.models.Model.delete()` raise
|
||||
:exc:`~exceptions.NotImplementedError`.
|
||||
|
||||
In practice, you probably won't need to use
|
||||
:class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
|
||||
they're used by Web requests, as explained in the next section.
|
||||
|
||||
Permission
|
||||
==========
|
||||
|
||||
.. class:: models.Permission
|
||||
|
||||
Fields
|
||||
------
|
||||
|
||||
:class:`~django.contrib.auth.models.Permission` objects have the following
|
||||
fields:
|
||||
|
||||
.. attribute:: name
|
||||
|
||||
Required. 50 characters or fewer. Example: ``'Can vote'``.
|
||||
|
||||
.. attribute:: content_type
|
||||
|
||||
Required. A reference to the ``django_content_type`` database table, which
|
||||
contains a record for each installed Django model.
|
||||
|
||||
.. attribute:: codename
|
||||
|
||||
Required. 100 characters or fewer. Example: ``'can_vote'``.
|
||||
|
||||
Methods
|
||||
-------
|
||||
|
||||
:class:`~django.contrib.auth.models.Permission` objects have the standard
|
||||
data-access methods like any other :doc:`Django model </ref/models/instances>`.
|
||||
|
||||
Group
|
||||
=====
|
||||
|
||||
.. class:: models.Group
|
||||
|
||||
Fields
|
||||
------
|
||||
|
||||
:class:`~django.contrib.auth.models.Group` objects have the following fields:
|
||||
|
||||
.. attribute:: name
|
||||
|
||||
Required. 80 characters or fewer. Any characters are permitted. Example:
|
||||
``'Awesome Users'``.
|
||||
|
||||
.. attribute:: permissions
|
||||
|
||||
Many-to-many field to :class:`~django.contrib.auth.models.Permission`::
|
||||
|
||||
group.permissions = [permission_list]
|
||||
group.permissions.add(permission, permission, ...)
|
||||
group.permissions.remove(permission, permission, ...)
|
||||
group.permissions.clear()
|
||||
|
||||
.. _topics-auth-signals:
|
||||
|
||||
Login and logout signals
|
||||
========================
|
||||
|
||||
.. module:: django.contrib.auth.signals
|
||||
|
||||
The auth framework uses two :doc:`signals </topics/signals>` that can be used
|
||||
for notification when a user logs in or out.
|
||||
|
||||
.. function:: django.contrib.auth.signals.user_logged_in
|
||||
|
||||
Sent when a user logs in successfully.
|
||||
|
||||
Arguments sent with this signal:
|
||||
|
||||
``sender``
|
||||
The class of the user that just logged in.
|
||||
|
||||
``request``
|
||||
The current :class:`~django.http.HttpRequest` instance.
|
||||
|
||||
``user``
|
||||
The user instance that just logged in.
|
||||
|
||||
.. function:: django.contrib.auth.signals.user_logged_out
|
||||
|
||||
Sent when the logout method is called.
|
||||
|
||||
``sender``
|
||||
As above: the class of the user that just logged out or ``None``
|
||||
if the user was not authenticated.
|
||||
|
||||
``request``
|
||||
The current :class:`~django.http.HttpRequest` instance.
|
||||
|
||||
``user``
|
||||
The user instance that just logged out or ``None`` if the
|
||||
user was not authenticated.
|
||||
|
||||
.. function:: django.contrib.auth.signals.user_login_failed
|
||||
|
||||
.. versionadded:: 1.5
|
||||
|
||||
Sent when the user failed to login successfully
|
||||
|
||||
``sender``
|
||||
The name of the module used for authentication.
|
||||
|
||||
``credentials``
|
||||
A dictionary of keyword arguments containing the user credentials that were
|
||||
passed to :func:`~django.contrib.auth.authenticate()` or your own custom
|
||||
authentication backend. Credentials matching a set of 'sensitive' patterns,
|
||||
(including password) will not be sent in the clear as part of the signal.
|
||||
|
||||
.. _authentication-backends-reference:
|
||||
|
||||
Authentication backends
|
||||
=======================
|
||||
|
||||
.. module:: django.contrib.auth.backends
|
||||
:synopsis: Django's built-in authentication backend classes.
|
||||
|
||||
This section details the authentication backends that come with Django. For
|
||||
information on how to use them and how to write your own authentication
|
||||
backends, see the :ref:`Other authentication sources section
|
||||
<authentication-backends>` of the :doc:`User authentication guide
|
||||
</topics/auth/index>`.
|
||||
|
||||
|
||||
Available authentication backends
|
||||
---------------------------------
|
||||
|
||||
The following backends are available in :mod:`django.contrib.auth.backends`:
|
||||
|
||||
.. class:: ModelBackend
|
||||
|
||||
This is the default authentication backend used by Django. It
|
||||
authenticates using usernames and passwords stored in the
|
||||
:class:`~django.contrib.auth.models.User` model.
|
||||
|
||||
|
||||
.. class:: RemoteUserBackend
|
||||
|
||||
Use this backend to take advantage of external-to-Django-handled
|
||||
authentication. It authenticates using usernames passed in
|
||||
:attr:`request.META['REMOTE_USER'] <django.http.HttpRequest.META>`. See
|
||||
the :doc:`Authenticating against REMOTE_USER </howto/auth-remote-user>`
|
||||
documentation.
|
||||
|
@ -56,7 +56,7 @@ auth
|
||||
|
||||
Django's authentication framework.
|
||||
|
||||
See :doc:`/topics/auth`.
|
||||
See :doc:`/topics/auth/index`.
|
||||
|
||||
comments
|
||||
========
|
||||
|
@ -1145,7 +1145,7 @@ changepassword
|
||||
.. django-admin:: changepassword
|
||||
|
||||
This command is only available if Django's :doc:`authentication system
|
||||
</topics/auth>` (``django.contrib.auth``) is installed.
|
||||
</topics/auth/index>` (``django.contrib.auth``) is installed.
|
||||
|
||||
Allows changing a user's password. It prompts you to enter twice the password of
|
||||
the user given as parameter. If they both match, the new password will be
|
||||
@ -1167,7 +1167,7 @@ createsuperuser
|
||||
.. django-admin:: createsuperuser
|
||||
|
||||
This command is only available if Django's :doc:`authentication system
|
||||
</topics/auth>` (``django.contrib.auth``) is installed.
|
||||
</topics/auth/index>` (``django.contrib.auth``) is installed.
|
||||
|
||||
Creates a superuser account (a user who has all permissions). This is
|
||||
useful if you need to create an initial superuser account but did not
|
||||
|
@ -5,7 +5,6 @@ API Reference
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
authbackends
|
||||
class-based-views/index
|
||||
clickjacking
|
||||
contrib/index
|
||||
|
@ -179,8 +179,8 @@ Authentication middleware
|
||||
.. class:: AuthenticationMiddleware
|
||||
|
||||
Adds the ``user`` attribute, representing the currently-logged-in user, to
|
||||
every incoming ``HttpRequest`` object. See :doc:`Authentication in Web requests
|
||||
</topics/auth>`.
|
||||
every incoming ``HttpRequest`` object. See :ref:`Authentication in Web requests
|
||||
<auth-web-requests>`.
|
||||
|
||||
CSRF protection middleware
|
||||
--------------------------
|
||||
|
@ -181,7 +181,7 @@ All attributes should be considered read-only, unless stated otherwise below.
|
||||
|
||||
``user`` is only available if your Django installation has the
|
||||
``AuthenticationMiddleware`` activated. For more, see
|
||||
:doc:`/topics/auth`.
|
||||
:doc:`/topics/auth/index`.
|
||||
|
||||
.. attribute:: HttpRequest.session
|
||||
|
||||
|
@ -107,8 +107,8 @@ AUTHENTICATION_BACKENDS
|
||||
Default: ``('django.contrib.auth.backends.ModelBackend',)``
|
||||
|
||||
A tuple of authentication backend classes (as strings) to use when attempting to
|
||||
authenticate a user. See the :doc:`authentication backends documentation
|
||||
</ref/authbackends>` for details.
|
||||
authenticate a user. See the :ref:`authentication backends documentation
|
||||
<authentication-backends>` for details.
|
||||
|
||||
.. setting:: AUTH_USER_MODEL
|
||||
|
||||
@ -2256,7 +2256,7 @@ AUTH_PROFILE_MODULE
|
||||
Default: Not defined
|
||||
|
||||
The site-specific user profile model used by this site. See
|
||||
:ref:`auth-profiles`.
|
||||
:ref:`User profiles <auth-profiles>`.
|
||||
|
||||
.. setting:: IGNORABLE_404_ENDS
|
||||
|
||||
|
@ -12,7 +12,7 @@ A list of all the signals that Django sends.
|
||||
The :doc:`comment framework </ref/contrib/comments/index>` sends a :doc:`set
|
||||
of comment-related signals </ref/contrib/comments/signals>`.
|
||||
|
||||
The :doc:`authentication framework </topics/auth>` sends :ref:`signals when
|
||||
The :doc:`authentication framework </topics/auth/index>` sends :ref:`signals when
|
||||
a user is logged in / out <topics-auth-signals>`.
|
||||
|
||||
Model signals
|
||||
|
@ -91,7 +91,7 @@ added in Django 1.2 alpha but not documented with the alpha release.
|
||||
|
||||
The default authentication backends shipped with Django do not
|
||||
currently make use of this, but third-party authentication backends
|
||||
are free to do so. See the :doc:`authentication docs </topics/auth>`
|
||||
are free to do so. See the :doc:`authentication docs </topics/auth/index>`
|
||||
for more information.
|
||||
|
||||
|
||||
@ -104,7 +104,7 @@ class will check the backend for permissions, just as the normal
|
||||
``User`` does. This is intended to help centralize permission
|
||||
handling; apps can always delegate the question of whether something
|
||||
is allowed or not to the authorization/authentication system. See the
|
||||
:doc:`authentication docs </topics/auth>` for more details.
|
||||
:doc:`authentication docs </topics/auth/index>` for more details.
|
||||
|
||||
|
||||
``select_related()`` improvements
|
||||
|
@ -165,7 +165,7 @@ A foundation for specifying permissions at the per-object level has been added.
|
||||
Although there is no implementation of this in core, a custom authentication
|
||||
backend can provide this implementation and it will be used by
|
||||
:class:`django.contrib.auth.models.User`. See the :doc:`authentication docs
|
||||
</topics/auth>` for more information.
|
||||
</topics/auth/index>` for more information.
|
||||
|
||||
Permissions for anonymous users
|
||||
-------------------------------
|
||||
@ -175,7 +175,7 @@ If you provide a custom auth backend with ``supports_anonymous_user`` set to
|
||||
User already did. This is useful for centralizing permission handling - apps
|
||||
can always delegate the question of whether something is allowed or not to
|
||||
the authorization/authentication backend. See the :doc:`authentication
|
||||
docs </topics/auth>` for more details.
|
||||
docs </topics/auth/index>` for more details.
|
||||
|
||||
Relaxed requirements for usernames
|
||||
----------------------------------
|
||||
|
@ -61,7 +61,7 @@ Permissions for inactive users
|
||||
If you provide a custom auth backend with ``supports_inactive_user`` set to
|
||||
``True``, an inactive user model will check the backend for permissions.
|
||||
This is useful for further centralizing the permission handling. See the
|
||||
:doc:`authentication docs </topics/auth>` for more details.
|
||||
:doc:`authentication docs </topics/auth/index>` for more details.
|
||||
|
||||
Backwards-incompatible changes in 1.3 alpha 2
|
||||
=============================================
|
||||
|
@ -254,7 +254,7 @@ Permissions for inactive users
|
||||
If you provide a custom auth backend with ``supports_inactive_user``
|
||||
set to ``True``, an inactive ``User`` instance will check the backend
|
||||
for permissions. This is useful for further centralizing the
|
||||
permission handling. See the :doc:`authentication docs </topics/auth>`
|
||||
permission handling. See the :doc:`authentication docs </topics/auth/index>`
|
||||
for more details.
|
||||
|
||||
GeoDjango
|
||||
|
2696
docs/topics/auth.txt
2696
docs/topics/auth.txt
File diff suppressed because it is too large
Load Diff
1074
docs/topics/auth/customizing.txt
Normal file
1074
docs/topics/auth/customizing.txt
Normal file
File diff suppressed because it is too large
Load Diff
1077
docs/topics/auth/default.txt
Normal file
1077
docs/topics/auth/default.txt
Normal file
File diff suppressed because it is too large
Load Diff
81
docs/topics/auth/index.txt
Normal file
81
docs/topics/auth/index.txt
Normal file
@ -0,0 +1,81 @@
|
||||
=============================
|
||||
User authentication in Django
|
||||
=============================
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
|
||||
default
|
||||
passwords
|
||||
customizing
|
||||
|
||||
.. module:: django.contrib.auth
|
||||
:synopsis: Django's authentication framework.
|
||||
|
||||
Django comes with an user authentication system. It handles user accounts,
|
||||
groups, permissions and cookie-based user sessions. This section of the
|
||||
documentation explains how the default implementation works out of the box, as
|
||||
well as how to :doc:`extend and customize </topics/auth/customizing>` it to
|
||||
suit your project's needs.
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
The Django authentication system handles both authentication and authorization.
|
||||
Briefly, authentication verifies a user is who they claim to be, and
|
||||
authorization determines what an authenticated user is allowed to do. Here the
|
||||
term authentication is used to refer to both tasks.
|
||||
|
||||
The auth system consists of:
|
||||
|
||||
* Users
|
||||
* Permissions: Binary (yes/no) flags designating whether a user may perform
|
||||
a certain task.
|
||||
* Groups: A generic way of applying labels and permissions to more than one
|
||||
user.
|
||||
* A configurable password hashing system
|
||||
* Forms and view tools for logging in users, or restricting content
|
||||
* A pluggable backend system
|
||||
|
||||
Installation
|
||||
============
|
||||
|
||||
Authentication support is bundled as a Django contrib module in
|
||||
``django.contrib.auth``. By default, the required configuration is already
|
||||
included in the :file:`settings.py` generated by :djadmin:`django-admin.py
|
||||
startproject <startproject>`, these consist of two items listed in your
|
||||
:setting:`INSTALLED_APPS` setting:
|
||||
|
||||
1. ``'django.contrib.auth'`` contains the core of the authentication framework,
|
||||
and its default models.
|
||||
2. ``'django.contrib.contenttypes'`` is the Django :doc:`content type system
|
||||
</ref/contrib/contenttypes>`, which allows permissions to be associated with
|
||||
models you create.
|
||||
|
||||
and two items in your :setting:`MIDDLEWARE_CLASSES` setting:
|
||||
|
||||
1. :class:`~django.contrib.sessions.middleware.SessionMiddleware` manages
|
||||
:doc:`sessions </topics/http/sessions>` across requests.
|
||||
2. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware` associates
|
||||
users with requests using sessions.
|
||||
|
||||
With these settings in place, running the command ``manage.py syncdb`` creates
|
||||
the necessary database tables for auth related models, creates permissions for
|
||||
any models defined in your installed apps, and prompts you to create
|
||||
a superuser account the first time you run it.
|
||||
|
||||
Usage
|
||||
=====
|
||||
|
||||
:doc:`Using Django's default implementation <default>`
|
||||
|
||||
* :ref:`Working with User objects <user-objects>`
|
||||
* :ref:`Permissions and authorization <topic-authorization>`
|
||||
* :ref:`Authentication in web requests <auth-web-requests>`
|
||||
* :ref:`Managing users in the admin <auth-admin>`
|
||||
|
||||
:doc:`API reference for the default implementation </ref/contrib/auth>`
|
||||
|
||||
:doc:`Customizing Users and authentication <customizing>`
|
||||
|
||||
:doc:`Password management in Django <passwords>`
|
212
docs/topics/auth/passwords.txt
Normal file
212
docs/topics/auth/passwords.txt
Normal file
@ -0,0 +1,212 @@
|
||||
=============================
|
||||
Password management in Django
|
||||
=============================
|
||||
|
||||
Password management is something that should generally not be reinvented
|
||||
unnecessarily, and Django endeavors to provide a secure and flexible set of
|
||||
tools for managing user passwords. This document describes how Django stores
|
||||
passwords, how the storage hashing can be configured, and some utilities to
|
||||
work with hashed passwords.
|
||||
|
||||
.. _auth_password_storage:
|
||||
|
||||
How Django stores passwords
|
||||
===========================
|
||||
|
||||
.. versionadded:: 1.4
|
||||
Django 1.4 introduces a new flexible password storage system and uses
|
||||
PBKDF2 by default. Previous versions of Django used SHA1, and other
|
||||
algorithms couldn't be chosen.
|
||||
|
||||
The :attr:`~django.contrib.auth.models.User.password` attribute of a
|
||||
:class:`~django.contrib.auth.models.User` object is a string in this format::
|
||||
|
||||
algorithm$hash
|
||||
|
||||
That's a storage algorithm, and hash, separated by the dollar-sign
|
||||
character. The algorithm is one of a number of one way hashing or password
|
||||
storage algorithms Django can use; see below. The hash is the result of the one-
|
||||
way function.
|
||||
|
||||
By default, Django uses the PBKDF2_ algorithm with a SHA256 hash, a
|
||||
password stretching mechanism recommended by NIST_. This should be
|
||||
sufficient for most users: it's quite secure, requiring massive
|
||||
amounts of computing time to break.
|
||||
|
||||
However, depending on your requirements, you may choose a different
|
||||
algorithm, or even use a custom algorithm to match your specific
|
||||
security situation. Again, most users shouldn't need to do this -- if
|
||||
you're not sure, you probably don't. If you do, please read on:
|
||||
|
||||
Django chooses the an algorithm by consulting the :setting:`PASSWORD_HASHERS`
|
||||
setting. This is a list of hashing algorithm classes that this Django
|
||||
installation supports. The first entry in this list (that is,
|
||||
``settings.PASSWORD_HASHERS[0]``) will be used to store passwords, and all the
|
||||
other entries are valid hashers that can be used to check existing passwords.
|
||||
This means that if you want to use a different algorithm, you'll need to modify
|
||||
:setting:`PASSWORD_HASHERS` to list your preferred algorithm first in the list.
|
||||
|
||||
The default for :setting:`PASSWORD_HASHERS` is::
|
||||
|
||||
PASSWORD_HASHERS = (
|
||||
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
|
||||
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
|
||||
'django.contrib.auth.hashers.BCryptPasswordHasher',
|
||||
'django.contrib.auth.hashers.SHA1PasswordHasher',
|
||||
'django.contrib.auth.hashers.MD5PasswordHasher',
|
||||
'django.contrib.auth.hashers.CryptPasswordHasher',
|
||||
)
|
||||
|
||||
This means that Django will use PBKDF2_ to store all passwords, but will support
|
||||
checking passwords stored with PBKDF2SHA1, bcrypt_, SHA1_, etc. The next few
|
||||
sections describe a couple of common ways advanced users may want to modify this
|
||||
setting.
|
||||
|
||||
.. _bcrypt_usage:
|
||||
|
||||
Using bcrypt with Django
|
||||
------------------------
|
||||
|
||||
Bcrypt_ is a popular password storage algorithm that's specifically designed
|
||||
for long-term password storage. It's not the default used by Django since it
|
||||
requires the use of third-party libraries, but since many people may want to
|
||||
use it Django supports bcrypt with minimal effort.
|
||||
|
||||
To use Bcrypt as your default storage algorithm, do the following:
|
||||
|
||||
1. Install the `py-bcrypt`_ library (probably by running ``sudo pip install
|
||||
py-bcrypt``, or downloading the library and installing it with ``python
|
||||
setup.py install``).
|
||||
|
||||
2. Modify :setting:`PASSWORD_HASHERS` to list ``BCryptPasswordHasher``
|
||||
first. That is, in your settings file, you'd put::
|
||||
|
||||
PASSWORD_HASHERS = (
|
||||
'django.contrib.auth.hashers.BCryptPasswordHasher',
|
||||
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
|
||||
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
|
||||
'django.contrib.auth.hashers.SHA1PasswordHasher',
|
||||
'django.contrib.auth.hashers.MD5PasswordHasher',
|
||||
'django.contrib.auth.hashers.CryptPasswordHasher',
|
||||
)
|
||||
|
||||
(You need to keep the other entries in this list, or else Django won't
|
||||
be able to upgrade passwords; see below).
|
||||
|
||||
That's it -- now your Django install will use Bcrypt as the default storage
|
||||
algorithm.
|
||||
|
||||
.. admonition:: Other bcrypt implementations
|
||||
|
||||
There are several other implementations that allow bcrypt to be
|
||||
used with Django. Django's bcrypt support is NOT directly
|
||||
compatible with these. To upgrade, you will need to modify the
|
||||
hashes in your database to be in the form `bcrypt$(raw bcrypt
|
||||
output)`. For example:
|
||||
`bcrypt$$2a$12$NT0I31Sa7ihGEWpka9ASYrEFkhuTNeBQ2xfZskIiiJeyFXhRgS.Sy`.
|
||||
|
||||
Increasing the work factor
|
||||
--------------------------
|
||||
|
||||
The PBKDF2 and bcrypt algorithms use a number of iterations or rounds of
|
||||
hashing. This deliberately slows down attackers, making attacks against hashed
|
||||
passwords harder. However, as computing power increases, the number of
|
||||
iterations needs to be increased. We've chosen a reasonable default (and will
|
||||
increase it with each release of Django), but you may wish to tune it up or
|
||||
down, depending on your security needs and available processing power. To do so,
|
||||
you'll subclass the appropriate algorithm and override the ``iterations``
|
||||
parameters. For example, to increase the number of iterations used by the
|
||||
default PBKDF2 algorithm:
|
||||
|
||||
1. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``::
|
||||
|
||||
from django.contrib.auth.hashers import PBKDF2PasswordHasher
|
||||
|
||||
class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
|
||||
"""
|
||||
A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
|
||||
"""
|
||||
iterations = PBKDF2PasswordHasher.iterations * 100
|
||||
|
||||
Save this somewhere in your project. For example, you might put this in
|
||||
a file like ``myproject/hashers.py``.
|
||||
|
||||
2. Add your new hasher as the first entry in :setting:`PASSWORD_HASHERS`::
|
||||
|
||||
PASSWORD_HASHERS = (
|
||||
'myproject.hashers.MyPBKDF2PasswordHasher',
|
||||
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
|
||||
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
|
||||
'django.contrib.auth.hashers.BCryptPasswordHasher',
|
||||
'django.contrib.auth.hashers.SHA1PasswordHasher',
|
||||
'django.contrib.auth.hashers.MD5PasswordHasher',
|
||||
'django.contrib.auth.hashers.CryptPasswordHasher',
|
||||
)
|
||||
|
||||
|
||||
That's it -- now your Django install will use more iterations when it
|
||||
stores passwords using PBKDF2.
|
||||
|
||||
Password upgrading
|
||||
------------------
|
||||
|
||||
When users log in, if their passwords are stored with anything other than
|
||||
the preferred algorithm, Django will automatically upgrade the algorithm
|
||||
to the preferred one. This means that old installs of Django will get
|
||||
automatically more secure as users log in, and it also means that you
|
||||
can switch to new (and better) storage algorithms as they get invented.
|
||||
|
||||
However, Django can only upgrade passwords that use algorithms mentioned in
|
||||
:setting:`PASSWORD_HASHERS`, so as you upgrade to new systems you should make
|
||||
sure never to *remove* entries from this list. If you do, users using un-
|
||||
mentioned algorithms won't be able to upgrade.
|
||||
|
||||
.. _sha1: http://en.wikipedia.org/wiki/SHA1
|
||||
.. _pbkdf2: http://en.wikipedia.org/wiki/PBKDF2
|
||||
.. _nist: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
|
||||
.. _bcrypt: http://en.wikipedia.org/wiki/Bcrypt
|
||||
.. _py-bcrypt: http://pypi.python.org/pypi/py-bcrypt/
|
||||
|
||||
|
||||
Manually managing a user's password
|
||||
===================================
|
||||
|
||||
.. module:: django.contrib.auth.hashers
|
||||
|
||||
.. versionadded:: 1.4
|
||||
The :mod:`django.contrib.auth.hashers` module provides a set of functions
|
||||
to create and validate hashed password. You can use them independently
|
||||
from the ``User`` model.
|
||||
|
||||
.. function:: check_password(password, encoded)
|
||||
|
||||
.. versionadded:: 1.4
|
||||
|
||||
If you'd like to manually authenticate a user by comparing a plain-text
|
||||
password to the hashed password in the database, use the convenience
|
||||
function :func:`django.contrib.auth.hashers.check_password`. It takes two
|
||||
arguments: the plain-text password to check, and the full value of a
|
||||
user's ``password`` field in the database to check against, and returns
|
||||
``True`` if they match, ``False`` otherwise.
|
||||
|
||||
.. function:: make_password(password[, salt, hashers])
|
||||
|
||||
.. versionadded:: 1.4
|
||||
|
||||
Creates a hashed password in the format used by this application. It takes
|
||||
one mandatory argument: the password in plain-text. Optionally, you can
|
||||
provide a salt and a hashing algorithm to use, if you don't want to use the
|
||||
defaults (first entry of ``PASSWORD_HASHERS`` setting).
|
||||
Currently supported algorithms are: ``'pbkdf2_sha256'``, ``'pbkdf2_sha1'``,
|
||||
``'bcrypt'`` (see :ref:`bcrypt_usage`), ``'sha1'``, ``'md5'``,
|
||||
``'unsalted_md5'`` (only for backward compatibility) and ``'crypt'``
|
||||
if you have the ``crypt`` library installed. If the password argument is
|
||||
``None``, an unusable password is returned (a one that will be never
|
||||
accepted by :func:`django.contrib.auth.hashers.check_password`).
|
||||
|
||||
.. function:: is_password_usable(encoded_password)
|
||||
|
||||
.. versionadded:: 1.4
|
||||
|
||||
Checks if the given string is a hashed password that has a chance
|
||||
of being verified against :func:`django.contrib.auth.hashers.check_password`.
|
@ -1063,52 +1063,46 @@ Proxy models are declared like normal models. You tell Django that it's a
|
||||
proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
|
||||
the ``Meta`` class to ``True``.
|
||||
|
||||
For example, suppose you want to add a method to the standard
|
||||
:class:`~django.contrib.auth.models.User` model that will be used in your
|
||||
templates. You can do it like this::
|
||||
For example, suppose you want to add a method to the ``Person`` model described
|
||||
above. You can do it like this::
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
class MyUser(User):
|
||||
class MyPerson(Person):
|
||||
class Meta:
|
||||
proxy = True
|
||||
|
||||
def do_something(self):
|
||||
...
|
||||
|
||||
The ``MyUser`` class operates on the same database table as its parent
|
||||
:class:`~django.contrib.auth.models.User` class. In particular, any new
|
||||
instances of :class:`~django.contrib.auth.models.User` will also be accessible
|
||||
through ``MyUser``, and vice-versa::
|
||||
The ``MyPerson`` class operates on the same database table as its parent
|
||||
``Person`` class. In particular, any new instances of ``Person`` will also be
|
||||
accessible through ``MyPerson``, and vice-versa::
|
||||
|
||||
>>> u = User.objects.create(username="foobar")
|
||||
>>> MyUser.objects.get(username="foobar")
|
||||
<MyUser: foobar>
|
||||
>>> p = Person.objects.create(first_name="foobar")
|
||||
>>> MyPerson.objects.get(first_name="foobar")
|
||||
<MyPerson: foobar>
|
||||
|
||||
You could also use a proxy model to define a different default ordering on a
|
||||
model. The standard :class:`~django.contrib.auth.models.User` model has no
|
||||
ordering defined on it (intentionally; sorting is expensive and we don't want
|
||||
to do it all the time when we fetch users). You might want to regularly order
|
||||
by the ``username`` attribute when you use the proxy. This is easy::
|
||||
You could also use a proxy model to define a different default ordering on
|
||||
a model. You might not always want to order the ``Person`` model, but regularly
|
||||
order by the ``last_name`` attribute when you use the proxy. This is easy::
|
||||
|
||||
class OrderedUser(User):
|
||||
class OrderedPerson(Person):
|
||||
class Meta:
|
||||
ordering = ["username"]
|
||||
ordering = ["last_name"]
|
||||
proxy = True
|
||||
|
||||
Now normal :class:`~django.contrib.auth.models.User` queries will be unordered
|
||||
and ``OrderedUser`` queries will be ordered by ``username``.
|
||||
Now normal ``Person`` queries will be unordered
|
||||
and ``OrderedPerson`` queries will be ordered by ``last_name``.
|
||||
|
||||
QuerySets still return the model that was requested
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
There is no way to have Django return, say, a ``MyUser`` object whenever you
|
||||
query for :class:`~django.contrib.auth.models.User` objects. A queryset for
|
||||
``User`` objects will return those types of objects. The whole point of proxy
|
||||
objects is that code relying on the original ``User`` will use those and your
|
||||
own code can use the extensions you included (that no other code is relying on
|
||||
anyway). It is not a way to replace the ``User`` (or any other) model
|
||||
everywhere with something of your own creation.
|
||||
There is no way to have Django return, say, a ``MyPerson`` object whenever you
|
||||
query for ``Person`` objects. A queryset for ``Person`` objects will return
|
||||
those types of objects. The whole point of proxy objects is that code relying
|
||||
on the original ``Person`` will use those and your own code can use the
|
||||
extensions you included (that no other code is relying on anyway). It is not
|
||||
a way to replace the ``Person`` (or any other) model everywhere with something
|
||||
of your own creation.
|
||||
|
||||
Base class restrictions
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
@ -1131,12 +1125,12 @@ it will become the default, although any managers defined on the parent
|
||||
classes will still be available.
|
||||
|
||||
Continuing our example from above, you could change the default manager used
|
||||
when you query the ``User`` model like this::
|
||||
when you query the ``Person`` model like this::
|
||||
|
||||
class NewManager(models.Manager):
|
||||
...
|
||||
|
||||
class MyUser(User):
|
||||
class MyPerson(Person):
|
||||
objects = NewManager()
|
||||
|
||||
class Meta:
|
||||
@ -1154,7 +1148,7 @@ containing the new managers and inherit that after the primary base class::
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
class MyUser(User, ExtraManagers):
|
||||
class MyPerson(Person, ExtraManagers):
|
||||
class Meta:
|
||||
proxy = True
|
||||
|
||||
|
@ -14,7 +14,7 @@ Introductions to all the key parts of Django you'll need to know:
|
||||
class-based-views/index
|
||||
files
|
||||
testing/index
|
||||
auth
|
||||
auth/index
|
||||
cache
|
||||
conditional-view-processing
|
||||
signing
|
||||
|
@ -651,7 +651,7 @@ Use the ``django.test.client.Client`` class to make requests.
|
||||
|
||||
.. method:: Client.login(**credentials)
|
||||
|
||||
If your site uses Django's :doc:`authentication system</topics/auth>`
|
||||
If your site uses Django's :doc:`authentication system</topics/auth/index>`
|
||||
and you deal with logging in users, you can use the test client's
|
||||
``login()`` method to simulate the effect of a user logging into the
|
||||
site.
|
||||
@ -695,7 +695,7 @@ Use the ``django.test.client.Client`` class to make requests.
|
||||
|
||||
.. method:: Client.logout()
|
||||
|
||||
If your site uses Django's :doc:`authentication system</topics/auth>`,
|
||||
If your site uses Django's :doc:`authentication system</topics/auth/index>`,
|
||||
the ``logout()`` method can be used to simulate the effect of a user
|
||||
logging out of your site.
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user