auth.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. =======================
  2. ``django.contrib.auth``
  3. =======================
  4. This document provides API reference material for the components of Django's
  5. authentication system. For more details on the usage of these components or
  6. how to customize authentication and authorization see the :doc:`authentication
  7. topic guide </topics/auth/index>`.
  8. .. currentmodule:: django.contrib.auth
  9. ``User`` model
  10. ==============
  11. Fields
  12. ------
  13. .. class:: models.User
  14. :class:`~django.contrib.auth.models.User` objects have the following
  15. fields:
  16. .. attribute:: username
  17. Required. 150 characters or fewer. Usernames may contain alphanumeric,
  18. ``_``, ``@``, ``+``, ``.`` and ``-`` characters.
  19. The ``max_length`` should be sufficient for many use cases. If you need
  20. a longer length, please use a :ref:`custom user model
  21. <specifying-custom-user-model>`. If you use MySQL with the ``utf8mb4``
  22. encoding (recommended for proper Unicode support), specify at most
  23. ``max_length=191`` because MySQL can only create unique indexes with
  24. 191 characters in that case by default.
  25. .. versionchanged:: 1.10
  26. The ``max_length`` increased from 30 to 150 characters.
  27. .. attribute:: first_name
  28. Optional. 30 characters or fewer.
  29. .. attribute:: last_name
  30. Optional. 30 characters or fewer.
  31. .. attribute:: email
  32. Optional. Email address.
  33. .. attribute:: password
  34. Required. A hash of, and metadata about, the password. (Django doesn't
  35. store the raw password.) Raw passwords can be arbitrarily long and can
  36. contain any character. See the :doc:`password documentation
  37. </topics/auth/passwords>`.
  38. .. attribute:: groups
  39. Many-to-many relationship to :class:`~django.contrib.auth.models.Group`
  40. .. attribute:: user_permissions
  41. Many-to-many relationship to :class:`~django.contrib.auth.models.Permission`
  42. .. attribute:: is_staff
  43. Boolean. Designates whether this user can access the admin site.
  44. .. attribute:: is_active
  45. Boolean. Designates whether this user account should be considered
  46. active. We recommend that you set this flag to ``False`` instead of
  47. deleting accounts; that way, if your applications have any foreign keys
  48. to users, the foreign keys won't break.
  49. This doesn't necessarily control whether or not the user can log in.
  50. Authentication backends aren't required to check for the ``is_active``
  51. flag but the default backend
  52. (:class:`~django.contrib.auth.backends.ModelBackend`) and the
  53. :class:`~django.contrib.auth.backends.RemoteUserBackend` do. You can
  54. use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`
  55. or :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend`
  56. if you want to allow inactive users to login. In this case, you'll also
  57. want to customize the
  58. :class:`~django.contrib.auth.forms.AuthenticationForm` used by the
  59. :func:`~django.contrib.auth.views.login` view as it rejects inactive
  60. users. Be aware that the permission-checking methods such as
  61. :meth:`~django.contrib.auth.models.User.has_perm` and the
  62. authentication in the Django admin all return ``False`` for inactive
  63. users.
  64. .. versionchanged:: 1.10
  65. In older versions,
  66. :class:`~django.contrib.auth.backends.ModelBackend` and
  67. :class:`~django.contrib.auth.backends.RemoteUserBackend` allowed
  68. inactive users to authenticate.
  69. .. attribute:: is_superuser
  70. Boolean. Designates that this user has all permissions without
  71. explicitly assigning them.
  72. .. attribute:: last_login
  73. A datetime of the user's last login.
  74. .. attribute:: date_joined
  75. A datetime designating when the account was created. Is set to the
  76. current date/time by default when the account is created.
  77. Methods
  78. -------
  79. .. class:: models.User
  80. .. method:: get_username()
  81. Returns the username for the user. Since the User model can be swapped
  82. out, you should use this method instead of referencing the username
  83. attribute directly.
  84. .. method:: is_anonymous()
  85. Always returns ``False``. This is a way of differentiating
  86. :class:`~django.contrib.auth.models.User` and
  87. :class:`~django.contrib.auth.models.AnonymousUser` objects.
  88. Generally, you should prefer using
  89. :meth:`~django.contrib.auth.models.User.is_authenticated()` to this
  90. method.
  91. .. method:: is_authenticated()
  92. Always returns ``True`` (as opposed to
  93. ``AnonymousUser.is_authenticated()`` which always returns ``False``).
  94. This is a way to tell if the user has been authenticated. This does not
  95. imply any permissions, and doesn't check if the user is active or has
  96. a valid session. Even though normally you will call this method on
  97. ``request.user`` to find out whether it has been populated by the
  98. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
  99. (representing the currently logged-in user), you should know this method
  100. returns ``True`` for any :class:`~django.contrib.auth.models.User`
  101. instance.
  102. .. method:: get_full_name()
  103. Returns the :attr:`~django.contrib.auth.models.User.first_name` plus
  104. the :attr:`~django.contrib.auth.models.User.last_name`, with a space in
  105. between.
  106. .. method:: get_short_name()
  107. Returns the :attr:`~django.contrib.auth.models.User.first_name`.
  108. .. method:: set_password(raw_password)
  109. Sets the user's password to the given raw string, taking care of the
  110. password hashing. Doesn't save the
  111. :class:`~django.contrib.auth.models.User` object.
  112. When the ``raw_password`` is ``None``, the password will be set to an
  113. unusable password, as if
  114. :meth:`~django.contrib.auth.models.User.set_unusable_password()`
  115. were used.
  116. .. method:: check_password(raw_password)
  117. Returns ``True`` if the given raw string is the correct password for
  118. the user. (This takes care of the password hashing in making the
  119. comparison.)
  120. .. method:: set_unusable_password()
  121. Marks the user as having no password set. This isn't the same as
  122. having a blank string for a password.
  123. :meth:`~django.contrib.auth.models.User.check_password()` for this user
  124. will never return ``True``. Doesn't save the
  125. :class:`~django.contrib.auth.models.User` object.
  126. You may need this if authentication for your application takes place
  127. against an existing external source such as an LDAP directory.
  128. .. method:: has_usable_password()
  129. Returns ``False`` if
  130. :meth:`~django.contrib.auth.models.User.set_unusable_password()` has
  131. been called for this user.
  132. .. method:: get_group_permissions(obj=None)
  133. Returns a set of permission strings that the user has, through their
  134. groups.
  135. If ``obj`` is passed in, only returns the group permissions for
  136. this specific object.
  137. .. method:: get_all_permissions(obj=None)
  138. Returns a set of permission strings that the user has, both through
  139. group and user permissions.
  140. If ``obj`` is passed in, only returns the permissions for this
  141. specific object.
  142. .. method:: has_perm(perm, obj=None)
  143. Returns ``True`` if the user has the specified permission, where perm
  144. is in the format ``"<app label>.<permission codename>"``. (see
  145. documentation on :ref:`permissions <topic-authorization>`). If the user is
  146. inactive, this method will always return ``False``.
  147. If ``obj`` is passed in, this method won't check for a permission for
  148. the model, but for this specific object.
  149. .. method:: has_perms(perm_list, obj=None)
  150. Returns ``True`` if the user has each of the specified permissions,
  151. where each perm is in the format
  152. ``"<app label>.<permission codename>"``. If the user is inactive,
  153. this method will always return ``False``.
  154. If ``obj`` is passed in, this method won't check for permissions for
  155. the model, but for the specific object.
  156. .. method:: has_module_perms(package_name)
  157. Returns ``True`` if the user has any permissions in the given package
  158. (the Django app label). If the user is inactive, this method will
  159. always return ``False``.
  160. .. method:: email_user(subject, message, from_email=None, **kwargs)
  161. Sends an email to the user. If ``from_email`` is ``None``, Django uses
  162. the :setting:`DEFAULT_FROM_EMAIL`. Any ``**kwargs`` are passed to the
  163. underlying :meth:`~django.core.mail.send_mail()` call.
  164. Manager methods
  165. ---------------
  166. .. class:: models.UserManager
  167. The :class:`~django.contrib.auth.models.User` model has a custom manager
  168. that has the following helper methods (in addition to the methods provided
  169. by :class:`~django.contrib.auth.models.BaseUserManager`):
  170. .. method:: create_user(username, email=None, password=None, **extra_fields)
  171. Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
  172. The :attr:`~django.contrib.auth.models.User.username` and
  173. :attr:`~django.contrib.auth.models.User.password` are set as given. The
  174. domain portion of :attr:`~django.contrib.auth.models.User.email` is
  175. automatically converted to lowercase, and the returned
  176. :class:`~django.contrib.auth.models.User` object will have
  177. :attr:`~django.contrib.auth.models.User.is_active` set to ``True``.
  178. If no password is provided,
  179. :meth:`~django.contrib.auth.models.User.set_unusable_password()` will
  180. be called.
  181. The ``extra_fields`` keyword arguments are passed through to the
  182. :class:`~django.contrib.auth.models.User`’s ``__init__`` method to
  183. allow setting arbitrary fields on a :ref:`custom User model
  184. <auth-custom-user>`.
  185. See :ref:`Creating users <topics-auth-creating-users>` for example usage.
  186. .. method:: create_superuser(username, email, password, **extra_fields)
  187. Same as :meth:`create_user`, but sets :attr:`~models.User.is_staff` and
  188. :attr:`~models.User.is_superuser` to ``True``.
  189. ``AnonymousUser`` object
  190. ========================
  191. .. class:: models.AnonymousUser
  192. :class:`django.contrib.auth.models.AnonymousUser` is a class that
  193. implements the :class:`django.contrib.auth.models.User` interface, with
  194. these differences:
  195. * :ref:`id <automatic-primary-key-fields>` is always ``None``.
  196. * :attr:`~django.contrib.auth.models.User.username` is always the empty
  197. string.
  198. * :meth:`~django.contrib.auth.models.User.get_username()` always returns
  199. the empty string.
  200. * :attr:`~django.contrib.auth.models.User.is_staff` and
  201. :attr:`~django.contrib.auth.models.User.is_superuser` are always
  202. ``False``.
  203. * :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
  204. * :attr:`~django.contrib.auth.models.User.groups` and
  205. :attr:`~django.contrib.auth.models.User.user_permissions` are always
  206. empty.
  207. * :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True``
  208. instead of ``False``.
  209. * :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
  210. ``False`` instead of ``True``.
  211. * :meth:`~django.contrib.auth.models.User.set_password()`,
  212. :meth:`~django.contrib.auth.models.User.check_password()`,
  213. :meth:`~django.db.models.Model.save` and
  214. :meth:`~django.db.models.Model.delete()` raise :exc:`NotImplementedError`.
  215. In practice, you probably won't need to use
  216. :class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
  217. they're used by Web requests, as explained in the next section.
  218. ``Permission`` model
  219. ====================
  220. .. class:: models.Permission
  221. Fields
  222. ------
  223. :class:`~django.contrib.auth.models.Permission` objects have the following
  224. fields:
  225. .. class:: models.Permission
  226. .. attribute:: name
  227. Required. 255 characters or fewer. Example: ``'Can vote'``.
  228. .. attribute:: content_type
  229. Required. A reference to the ``django_content_type`` database table,
  230. which contains a record for each installed model.
  231. .. attribute:: codename
  232. Required. 100 characters or fewer. Example: ``'can_vote'``.
  233. Methods
  234. -------
  235. :class:`~django.contrib.auth.models.Permission` objects have the standard
  236. data-access methods like any other :doc:`Django model </ref/models/instances>`.
  237. ``Group`` model
  238. ===============
  239. .. class:: models.Group
  240. Fields
  241. ------
  242. :class:`~django.contrib.auth.models.Group` objects have the following fields:
  243. .. class:: models.Group
  244. .. attribute:: name
  245. Required. 80 characters or fewer. Any characters are permitted. Example:
  246. ``'Awesome Users'``.
  247. .. attribute:: permissions
  248. Many-to-many field to :class:`~django.contrib.auth.models.Permission`::
  249. group.permissions.set([permission_list])
  250. group.permissions.add(permission, permission, ...)
  251. group.permissions.remove(permission, permission, ...)
  252. group.permissions.clear()
  253. .. _topics-auth-signals:
  254. Login and logout signals
  255. ========================
  256. .. module:: django.contrib.auth.signals
  257. The auth framework uses the following :doc:`signals </topics/signals>` that
  258. can be used for notification when a user logs in or out.
  259. .. function:: user_logged_in
  260. Sent when a user logs in successfully.
  261. Arguments sent with this signal:
  262. ``sender``
  263. The class of the user that just logged in.
  264. ``request``
  265. The current :class:`~django.http.HttpRequest` instance.
  266. ``user``
  267. The user instance that just logged in.
  268. .. function:: user_logged_out
  269. Sent when the logout method is called.
  270. ``sender``
  271. As above: the class of the user that just logged out or ``None``
  272. if the user was not authenticated.
  273. ``request``
  274. The current :class:`~django.http.HttpRequest` instance.
  275. ``user``
  276. The user instance that just logged out or ``None`` if the
  277. user was not authenticated.
  278. .. function:: user_login_failed
  279. Sent when the user failed to login successfully
  280. ``sender``
  281. The name of the module used for authentication.
  282. ``credentials``
  283. A dictionary of keyword arguments containing the user credentials that were
  284. passed to :func:`~django.contrib.auth.authenticate()` or your own custom
  285. authentication backend. Credentials matching a set of 'sensitive' patterns,
  286. (including password) will not be sent in the clear as part of the signal.
  287. .. _authentication-backends-reference:
  288. Authentication backends
  289. =======================
  290. .. module:: django.contrib.auth.backends
  291. :synopsis: Django's built-in authentication backend classes.
  292. This section details the authentication backends that come with Django. For
  293. information on how to use them and how to write your own authentication
  294. backends, see the :ref:`Other authentication sources section
  295. <authentication-backends>` of the :doc:`User authentication guide
  296. </topics/auth/index>`.
  297. Available authentication backends
  298. ---------------------------------
  299. The following backends are available in :mod:`django.contrib.auth.backends`:
  300. .. class:: ModelBackend
  301. This is the default authentication backend used by Django. It
  302. authenticates using credentials consisting of a user identifier and
  303. password. For Django's default user model, the user identifier is the
  304. username, for custom user models it is the field specified by
  305. USERNAME_FIELD (see :doc:`Customizing Users and authentication
  306. </topics/auth/customizing>`).
  307. It also handles the default permissions model as defined for
  308. :class:`~django.contrib.auth.models.User` and
  309. :class:`~django.contrib.auth.models.PermissionsMixin`.
  310. :meth:`has_perm`, :meth:`get_all_permissions`, :meth:`get_user_permissions`,
  311. and :meth:`get_group_permissions` allow an object to be passed as a
  312. parameter for object-specific permissions, but this backend does not
  313. implement them other than returning an empty set of permissions if
  314. ``obj is not None``.
  315. .. method:: authenticate(username=None, password=None, **kwargs)
  316. Tries to authenticate ``username`` with ``password`` by calling
  317. :meth:`User.check_password
  318. <django.contrib.auth.models.User.check_password>`. If no ``username``
  319. is provided, it tries to fetch a username from ``kwargs`` using the
  320. key :attr:`CustomUser.USERNAME_FIELD
  321. <django.contrib.auth.models.CustomUser.USERNAME_FIELD>`. Returns an
  322. authenticated user or ``None``.
  323. .. method:: get_user_permissions(user_obj, obj=None)
  324. Returns the set of permission strings the ``user_obj`` has from their
  325. own user permissions. Returns an empty set if
  326. :meth:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or
  327. :attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.
  328. .. method:: get_group_permissions(user_obj, obj=None)
  329. Returns the set of permission strings the ``user_obj`` has from the
  330. permissions of the groups they belong. Returns an empty set if
  331. :meth:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or
  332. :attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.
  333. .. method:: get_all_permissions(user_obj, obj=None)
  334. Returns the set of permission strings the ``user_obj`` has, including both
  335. user permissions and group permissions. Returns an empty set if
  336. :meth:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or
  337. :attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.
  338. .. method:: has_perm(user_obj, perm, obj=None)
  339. Uses :meth:`get_all_permissions` to check if ``user_obj`` has the
  340. permission string ``perm``. Returns ``False`` if the user is not
  341. :attr:`~django.contrib.auth.models.CustomUser.is_active`.
  342. .. method:: has_module_perms(self, user_obj, app_label)
  343. Returns whether the ``user_obj`` has any permissions on the app
  344. ``app_label``.
  345. .. method:: ModelBackend.user_can_authenticate()
  346. .. versionadded:: 1.10
  347. Returns whether the user is allowed to authenticate. To match the
  348. behavior of :class:`~django.contrib.auth.forms.AuthenticationForm`
  349. which :meth:`prohibits inactive users from logging in
  350. <django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed>`,
  351. this method returns ``False`` for users with :attr:`is_active=False
  352. <django.contrib.auth.models.User.is_active>`. Custom user models that
  353. don't have an :attr:`~django.contrib.auth.models.CustomUser.is_active`
  354. field are allowed.
  355. .. class:: AllowAllUsersModelBackend
  356. .. versionadded:: 1.10
  357. Same as :class:`ModelBackend` except that it doesn't reject inactive users
  358. because :meth:`~ModelBackend.user_can_authenticate` always returns ``True``.
  359. When using this backend, you'll likely want to customize the
  360. :class:`~django.contrib.auth.forms.AuthenticationForm` used by the
  361. :func:`~django.contrib.auth.views.login` view by overriding the
  362. :meth:`~django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed`
  363. method as it rejects inactive users.
  364. .. class:: RemoteUserBackend
  365. Use this backend to take advantage of external-to-Django-handled
  366. authentication. It authenticates using usernames passed in
  367. :attr:`request.META['REMOTE_USER'] <django.http.HttpRequest.META>`. See
  368. the :doc:`Authenticating against REMOTE_USER </howto/auth-remote-user>`
  369. documentation.
  370. If you need more control, you can create your own authentication backend
  371. that inherits from this class and override these attributes or methods:
  372. .. attribute:: RemoteUserBackend.create_unknown_user
  373. ``True`` or ``False``. Determines whether or not a
  374. :class:`~django.contrib.auth.models.User` object is created if not already
  375. in the database. Defaults to ``True``.
  376. .. method:: RemoteUserBackend.authenticate(remote_user)
  377. The username passed as ``remote_user`` is considered trusted. This method
  378. simply returns the ``User`` object with the given username, creating a new
  379. ``User`` object if :attr:`~RemoteUserBackend.create_unknown_user` is
  380. ``True``.
  381. Returns ``None`` if :attr:`~RemoteUserBackend.create_unknown_user` is
  382. ``False`` and a ``User`` object with the given username is not found in the
  383. database.
  384. .. method:: RemoteUserBackend.clean_username(username)
  385. Performs any cleaning on the ``username`` (e.g. stripping LDAP DN
  386. information) prior to using it to get or create a
  387. :class:`~django.contrib.auth.models.User` object. Returns the cleaned
  388. username.
  389. .. method:: RemoteUserBackend.configure_user(user)
  390. Configures a newly created user. This method is called immediately after a
  391. new user is created, and can be used to perform custom setup actions, such
  392. as setting the user's groups based on attributes in an LDAP directory.
  393. Returns the user object.
  394. .. method:: RemoteUserBackend.user_can_authenticate()
  395. .. versionadded:: 1.10
  396. Returns whether the user is allowed to authenticate. This method returns
  397. ``False`` for users with :attr:`is_active=False
  398. <django.contrib.auth.models.User.is_active>`. Custom user models that don't
  399. have an :attr:`~django.contrib.auth.models.CustomUser.is_active` field are
  400. allowed.
  401. .. class:: AllowAllUsersRemoteUserBackend
  402. .. versionadded:: 1.10
  403. Same as :class:`RemoteUserBackend` except that it doesn't reject inactive
  404. users because :attr:`~RemoteUserBackend.user_can_authenticate` always
  405. returns ``True``.