Django中的用户认证

Django comes with a user authentication system. It handles user accounts,groups, permissions and cookie-based user sessions. This section of thedocumentation explains how the default implementation works out of the box, aswell as how to extend and customize it tosuit your project's needs.

概况

The Django authentication system handles both authentication and authorization.Briefly, authentication verifies a user is who they claim to be, andauthorization determines what an authenticated user is allowed to do. Here theterm authentication is used to refer to both tasks.

认证系统由以下部分组成:

  • Users
  • Permissions: Binary (yes/no) flags designating whether a user may performa certain task.
  • Groups: A generic way of applying labels and permissions to more than oneuser.
  • A configurable password hashing system
  • Forms and view tools for logging in users, or restricting content
  • A pluggable backend system
    The authentication system in Django aims to be very generic and doesn't providesome features commonly found in web authentication systems. Solutions for someof these common problems have been implemented in third-party packages:

  • 密码强度检查

  • 限制登录尝试
  • 针对第三方的身份验证(例如OAuth)
  • Object-level permissions

安装

Authentication support is bundled as a Django contrib module indjango.contrib.auth. By default, the required configuration is alreadyincluded in the settings.py generated by django-admin
startproject
, these consist of two items listed in yourINSTALLED_APPS setting:

  • 'django.contrib.auth' contains the core of the authentication framework,and its default models.
  • 'django.contrib.contenttypes' is the Django content type system, which allows permissions to be associated withmodels you create.
    and these items in your MIDDLEWARE setting:

  • SessionMiddleware managessessions across requests.

  • AuthenticationMiddleware associatesusers with requests using sessions.
    有了这些设置,运行命令 manage.py migrate 为auth相关模型创建必要的数据表,并为已安装应用中定义的任何模型创建许可。

Usage

Using Django's default implementation

Customizing Users and authentication

Password management in Django