Django用户认证(User authentication in Django)

Django提供了一个用户身份验证系统, 它处理用户帐户、组权限和基于cookie的用户会话。文档这部分解释默认实现是如何工作的, 以及如何 扩展和定制 以适应您的项目.

综述

Django身份验证系统处理身份验证和授权. 简单说, 身份验证用于验证用户, 授权决定允许已认证用户能进行什么操作. 在这里术语 authentication 用于指代两种任务.

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

The authentication system in Django aims to be very generic and doesn’t provide some features commonly found in web authentication systems. Solutions for some of these common problems have been implemented in third-party packages:

  • Password strength checking
  • Throttling of login attempts
  • Authentication against third-parties (OAuth, for example)

安装

认证功能由Django contrib模块提供 django.contrib.auth. 默认情况下, 依赖配置已经包含在配置文件中 settings.py 由命令 django-admin startproject 生成, 包含两个 INSTALLED_APPS 设置:

  1. 'django.contrib.auth' 包含认证框架的核心, 为默认模块.
  2. 'django.contrib.contenttypes' 是Django content type system, 它允许您将创建的模型与权限关联.

一下 MIDDLEWARE 设置:

  1. SessionMiddleware 管理跨请求 会话(sessions).
  2. AuthenticationMiddleware 通过会话(sessions)将用户和请求关联起来.

有了这些设置, 运行命令 manage.py migrate 创建所有在你 apps 中定义的与 auth有关的模型和权限的表结构.