---
title: "django.contrib.auth"
version: 1.10
locale: ja
source: https://docs.djangoproject.com/ja/1.10/ref/contrib/auth/
canonical: https://djangodocs.dev/ja/1.10/ref/contrib/auth/
---
# `django.contrib.auth`

このドキュメントでは、Django の 認証システムのコンポーネントの API リファレンス資料を提供しています。 これらのコンポーネントの使い方や、認証と承認をカスタマイズする方法の詳細は、 [認証トピックガイド](/ja/1.10/topics/auth/) を参照してください。

## `User` モデル

### フィールド

#### `class models.User`

[`User`](#id1) オブジェクトには、以下のフィールドがあります:

#### `username`

必須です。150 文字以下です。英数字のほか、`_`、`@`、`+`、`.`、`-` が使えます。

`max_length` は多くの状況で十分のはずです。もしより長い文字数が必要な場合は、[独自のユーザモデル](/ja/1.10/topics/auth/customizing/#specifying-custom-user-model) を参照してください。`utf8mb4` エンコーディングで MySQL を使っている場合は (適切な Unicode をサポートするために推奨されています)、最大でも `max_length=191` としてください。なぜなら、MySQL は、でおフォルトでは 191 文字まででしかユニークインデックスを作成できないからです。

> **ユーザ名と Unicode**
>
> Django はもともと ASCII 文字のみをユーザ名に受け入れていました。意図的ではないにせよ、Unicode 文字列は Python 3 を使用しているときにはいつも受け入れられてきました。Django 1.10 は、公式にユーザ名での Unicode サポートを追加しました。Python 2 では、引き続きASCII のみの動作です。

> **Changed in Django 1.10**
>
> `max_length` は 30 文字から 150 文字に引き上げられました。

#### `first_name`

省略可能です。30文字以下です。

#### `last_name`

省略可能です。30文字以下です。

#### `email`

省略可能です。E メールアドレスです。

#### `password`

必須です。パスワードのハッシュであり、パスワードについてのメタデータでもあります。(Django は生のパスワードを保管しません。) 生のパスワードは、任意の長さで、あらゆる文字を使用可能です。詳しくは [password documentation](/ja/1.10/topics/auth/passwords/) を参照してください。

#### `groups`

[`Group`](#id6) への多対多のリレーションシップです。

#### `user_permissions`

[`Permission`](#id3) への多対多のリレーションシップです。

#### `is_staff`

真偽値です。ユーザが admin サイトにアクセスできるかどうかを指定します。

#### `is_active`

真偽値です。 このユーザアカウントをアクティブと見なすかどうかを指定します。 アカウントを削除するのではなく、このフラグを `False` に設定することをお勧めします。 そうすれば、アプリケーションに外部キーがある場合でも、外部キーが破損しません。

この属性は、必ずしもユーザがログインできるかどうかをコントロールするわけではありません。認証バックエンドは必ずしも `is_active` フラグをチェックしませんが、デフォルトのバックエンド ([`ModelBackend`](#django.contrib.auth.backends.ModelBackend)) と [`RemoteUserBackend`](#django.contrib.auth.backends.RemoteUserBackend) はチェックを行います。非アクティブのユーザがログインできるようにしたい場合は、[`AllowAllUsersModelBackend`](#django.contrib.auth.backends.AllowAllUsersModelBackend) や [`AllowAllUsersRemoteUserBackend`](#django.contrib.auth.backends.AllowAllUsersRemoteUserBackend) を使うことができます。この場合、非アクティブのユーザを拒否してしまうので、[`login()`](/ja/1.10/topics/auth/default/#django.contrib.auth.views.login) によって使われる [`AuthenticationForm`](/ja/1.10/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm) もカスタマイズした方が良いでしょう。[`has_perm()`](#django.contrib.auth.models.User.has_perm) のようなパーミッションチェックのメソッドや Django admin 内の認証はすべて非アクティブユーザに対して `False` を返すことに注意してください。

> **Changed in Django 1.10**
>
> 古いバージョンでは、[`ModelBackend`](#django.contrib.auth.backends.ModelBackend) や [`RemoteUserBackend`](#django.contrib.auth.backends.RemoteUserBackend) は非アクティブのユーザが認証できるようになっていました。

#### `is_superuser`

真偽値です。明示的にアサインすることなく全てのパーミッションを持たせるかどうかを指定します。

#### `last_login`

ユーザーが最後にログインした日時です。

#### `date_joined`

いつアカウントが作成されたかを示す日時です。アカウントが作成されたとき、デフォルトでは現在の日時がセットされます。

### 属性

#### `class models.User`

#### `is_authenticated`

(`AnonymousUser.is_authenticated` が常に `False` なのとは対照的に) 常に `True` の読み取り専用属性です。ユーザが認証済みかどうかを知らせる方法です。これはパーミッションという意味ではなく、ユーザーがアクティブかどうか、また有効なセッションがあるかどうかをチェックするわけでもありません。 通常、`request.user` のこの属性をチェックして [`AuthenticationMiddleware`](/ja/1.10/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware) (現在ログイン中のユーザを表します) によって格納されているかどうかを調べます。[`User`](#id1) のインスタンスの場合、この属性は `True` となります。

> **Changed in Django 1.10**
>
> 古いバージョンでは、メソッドでした。メソッドとして使うための後方互換性サポートは、Django 2.0 で廃止されます。

#### `is_anonymous`

常に `False` の読み取り専用属性です。[`User`](#id1) オブジェクトと [`AnonymousUser`](#django.contrib.auth.models.AnonymousUser) オブジェクトを区別する方法です。一般的に、[`is_authenticated`](#django.contrib.auth.models.User.is_authenticated) を使う方が好ましいと言えます。

> **Changed in Django 1.10**
>
> 古いバージョンでは、メソッドでした。メソッドとして使うための後方互換性サポートは、Django 2.0 で廃止されます。

### メソッド

#### `class models.User`

#### `get_username()`

ユーザのユーザ名を返します。`User` モデルはスワップアウトされることがあるので、ユーザ名を直接参照する代わりにこのメソッドを使う必要があります。

#### `get_full_name()`

[`first_name`](#django.contrib.auth.models.User.first_name) と [`last_name`](#django.contrib.auth.models.User.last_name) をスペースでつないだ文字列を返します。

#### `get_short_name()`

[`first_name`](#django.contrib.auth.models.User.first_name) を返します。

#### `set_password(raw_password)`

指定された生の文字列に、ユーザのパスワードをセットし、パスワードのハッシュ処理を行います。[`User`](#id1) は保存しません。

`raw_password` が `None` のとき、[`set_unusable_password()`](#django.contrib.auth.models.User.set_unusable_password) が使われるのと同じように、パスワードは使用に適さないパスワードになります。

#### `check_password(raw_password)`

与えられた生の文字列が、ユーザに対して正しいパスワードであれば `True` を返します。 (比較する際にはパスワードハッシュを処理します。)

#### `set_unusable_password()`

ユーザにパスワードが設定されていないものとしてマークします。これは、パスワードに空の文字列を付けることと同じではありません。ユーザに対する [`check_password()`](#django.contrib.auth.models.User.check_password) は `True` を返しません。[`User`](#id1) オブジェクトを保存しません。

アプリケーションの認証が LDAP ディレクトリなどの既存の外部ソースに対して行われている場合は、これが必要になることがあります。

#### `has_usable_password()`

ユーザに対して [`set_unusable_password()`](#django.contrib.auth.models.User.set_unusable_password) が呼ばれている場合、`False` を返します。

#### `get_group_permissions(obj=None)`

ユーザがグループを通して持つパーミッションの文字列のセットを返します。

`obj` が渡されたとき、指定されたオブジェクトに対するグループパーミッションのみを返します。

#### `get_all_permissions(obj=None)`

ユーザがグループおよびユーザパーミッションを通して持つパーミッションの文字列のセットを返します。

`obj` が渡された場合、指定されたオブジェクトに対するパーミッションのみを返します。

#### `has_perm(perm, obj=None)`

ユーザが指定されたパーミッションを持っている場合、`True` を返します。perm は `"<app label>.<permission codename>"` 形式です。([permissions](/ja/1.10/topics/auth/default/#topic-authorization) のドキュメントを参照)。ユーザが非アクティブの場合、このメソッドは常に `False` を返します。

`obj` が渡された場合、このメソッドは指定されたオブジェクトに対してパーミッションのチェックを行い、モデルに対しては行いません。

#### `has_perms(perm_list, obj=None)`

ユーザが指定されたそれぞれのパーミッションを持っている場合、`True` を返します。各パーミッションは `"<app label>.<permission codename>"` 形式です。ユーザが非アクティブの場合、このメソッドは常に `False` を返します。

`obj` が渡された場合、このメソッドは指定されたオブジェクトに対してパーミッションのチェックを行い、モデルに対しては行いません。

#### `has_module_perms(package_name)`

ユーザが指定されたパッケージ (Django のアプリケーションラベル)内の全パーミッションを持っている場合、`True` を返します。ユーザが非アクティブの場合、このメソッドは常に `False` を返します。

#### `email_user(subject, message, from_email=None, **kwargs)`

ユーザに E メール送信します。`from_email` が `None` の場合、Django は [`DEFAULT_FROM_EMAIL`](/ja/1.10/ref/settings/#std-setting-DEFAULT_FROM_EMAIL) を使用します。全ての `**kwargs` は元となる [`send_mail()`](/ja/1.10/topics/email/#django.core.mail.send_mail) 呼び出しに渡されます。

### マネージャメソッド

#### `class models.UserManager`

[`User`](#id1) モデルは、([`BaseUserManager`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.BaseUserManager) で提供されるメソッドに加えて) 以下のヘルパーメソッドを有する独自のマネージャを持っています:

#### `create_user(username, email=None, password=None, **extra_fields)`

[`User`](#id1) を作成、保存して返します。

The [`username`](#django.contrib.auth.models.User.username) and
[`password`](#django.contrib.auth.models.User.password) are set as given. The
domain portion of [`email`](#django.contrib.auth.models.User.email) is
automatically converted to lowercase, and the returned
[`User`](#id1) object will have
[`is_active`](#django.contrib.auth.models.User.is_active) set to `True`.

If no password is provided,
[`set_unusable_password()`](#django.contrib.auth.models.User.set_unusable_password) will
be called.

The `extra_fields` keyword arguments are passed through to the
[`User`](#id1)’s `__init__` method to
allow setting arbitrary fields on a [custom user model](/ja/1.10/topics/auth/customizing/#auth-custom-user).

See [Creating users](/ja/1.10/topics/auth/default/#topics-auth-creating-users) for example usage.

#### `create_superuser(username, email, password, **extra_fields)`

[`create_user()`](#django.contrib.auth.models.UserManager.create_user) と同じですが、[`is_staff`](#django.contrib.auth.models.User.is_staff) と [`is_superuser`](#django.contrib.auth.models.User.is_superuser) を `True` にセットします。

## `AnonymousUser` オブジェクト

#### `class models.AnonymousUser`

[`django.contrib.auth.models.AnonymousUser`](#django.contrib.auth.models.AnonymousUser) は、[`django.contrib.auth.models.User`](#id1) インターフェースを実装するクラスで、以下の点が異なります。

- [id](/ja/1.10/topics/db/models/#automatic-primary-key-fields) が常に `None` です。
- [`username`](#django.contrib.auth.models.User.username) が常に空の文字列です。
- [`get_username()`](#django.contrib.auth.models.User.get_username) が常に空の文字列を返します。
- [`is_anonymous`](#django.contrib.auth.models.User.is_anonymous) が `False` ではなく `True` です。
- [`is_authenticated`](#django.contrib.auth.models.User.is_authenticated) が `False` ではなく `True` です。
- [`is_staff`](#django.contrib.auth.models.User.is_staff) と [`is_superuser`](#django.contrib.auth.models.User.is_superuser) が常に `False` です。
- [`is_active`](#django.contrib.auth.models.User.is_active) が常に `False` です。
- [`groups`](#django.contrib.auth.models.User.groups) と [`user_permissions`](#django.contrib.auth.models.User.user_permissions) が常に空です。
- [`set_password()`](#django.contrib.auth.models.User.set_password)、[`check_password()`](#django.contrib.auth.models.User.check_password)、[`save()`](/ja/1.10/ref/models/instances/#django.db.models.Model.save)、[`delete()`](/ja/1.10/ref/models/instances/#django.db.models.Model.delete) が [`NotImplementedError`](https://docs.python.org/3/library/exceptions.html#NotImplementedError) を投げます。

実際には、[`AnonymousUser`](#django.contrib.auth.models.AnonymousUser) オブジェクトを自分自身で使う必要はないかもしれませんが、次のセクションで説明するように、Web リクエストで使用されます。

## `Permission` モデル

#### `class models.Permission`

### フィールド

[`Permission`](#id3) オブジェクトには以下のフィールドがあります:

#### `class models.Permission`

#### `name`

必須です。255 文字以下です。例: `'Can vote'`。

#### `content_type`

必須です。`django_content_type` データベーステーブルへの参照で、インストールされた各モデルのレコードを含みます。

#### `codename`

必須です。100 文字以下です。例: `'can_vote'`。

### メソッド

他のあらゆる [Django モデル](/ja/1.10/ref/models/instances/) と同じように、[`Permission`](#id3) オブジェクトも標準的なデータアクセスのメソッドが使えます。

## `Group` モデル

#### `class models.Group`

### フィールド

[`Group`](#id6) オブジェクトには以下のフィールドがあります:

#### `class models.Group`

#### `name`

必須です。80以下です。あらゆる文字列が使えます。例: `'Awesome Users'`。

#### `permissions`

[`Permission`](#id3) への多対多のフィールドです:

```
group.permissions.set([permission_list])
group.permissions.add(permission, permission, ...)
group.permissions.remove(permission, permission, ...)
group.permissions.clear()
```

## バリデータ

#### `class validators.ASCIIUsernameValidator`

> **New in Django 1.10**

ASCII 文字列に加えて、`@`、`.`、`+`、`-`、`_` のみを許容するバリデータです。Python 2 での `User.username` に対するデフォルトのバリデータです。

#### `class validators.UnicodeUsernameValidator`

> **New in Django 1.10**

Unicode 文字列に加えて、`@`、`.`、`+`、`-`、`_` を許容するバリデータです。Python 3 での `User.username` に対するデフォルトのバリデータです。

## ログインとログアウトのシグナル

認証フレームワークは、ユーザーがログインやログアウトをしたときの通知に使うことができる、以下の [signals](/ja/1.10/topics/signals/) を使用します。

#### `user_logged_in()`

ユーザがログインに成功したときに送信されます。

このシグナルとともに送信される引数は以下の通りです:

**`sender`**

  たった今ログインしたユーザのクラスです。

**`request`**

  現在の [`HttpRequest`](/ja/1.10/ref/request-response/#django.http.HttpRequest) インスタンスです。

**`user`**

  たった今ログインしたユーザのインスタンスです。

#### `user_logged_out()`

logout メソッドが呼ばれたときに送信されます。

**`sender`**

  上記の通り: たった今ログアウトしたユーザのクラス、もしくはユーザが認証されなかった場合は `None` となります。

**`request`**

  現在の [`HttpRequest`](/ja/1.10/ref/request-response/#django.http.HttpRequest) インスタンスです。

**`user`**

  たった今ログアウトしたユーザのインスタンスか、ユーザが認証されなかった場合は None\`\`です。

#### `user_login_failed()`

ユーザがログインに失敗したときに送信されます。

**`sender`**

  認証のために使われるモジュールの名前です。

**`credentials`**

  [`authenticate()`](/ja/1.10/topics/auth/default/#django.contrib.auth.authenticate) か独自の認証バックエンドに渡されたユーザ資格情報を含む、キーワード引数のディクショナリです。'sensitive' パターンのセットに一致する (パスワードを含んだ) 資格情報は、シグナルの一部として明確には送信されません。

## 認証のバックエンド

このセクションでは、Django に付属する認証バックエンドについて詳しく説明します。 使用方法と独自の認証バックエンドの作成方法については、[ユーザ認証ガイド](/ja/1.10/topics/auth/) の [他の認証ソースのセクション](/ja/1.10/topics/auth/customizing/#authentication-backends) を参照してください。

### 利用可能な認証バックエンド

以下のバックエンドが [`django.contrib.auth.backends`](#module-django.contrib.auth.backends) 内で利用可能です:

#### `class ModelBackend`

This is the default authentication backend used by Django.  It
authenticates using credentials consisting of a user identifier and
password.  For Django's default user model, the user identifier is the
username, for custom user models it is the field specified by
USERNAME\_FIELD (see [Customizing Users and authentication](/ja/1.10/topics/auth/customizing/)).

It also handles the default permissions model as defined for
[`User`](#id1) and
[`PermissionsMixin`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.PermissionsMixin).

[`has_perm()`](#django.contrib.auth.backends.ModelBackend.has_perm), [`get_all_permissions()`](#django.contrib.auth.backends.ModelBackend.get_all_permissions), [`get_user_permissions()`](#django.contrib.auth.backends.ModelBackend.get_user_permissions),
and [`get_group_permissions()`](#django.contrib.auth.backends.ModelBackend.get_group_permissions) allow an object to be passed as a
parameter for object-specific permissions, but this backend does not
implement them other than returning an empty set of permissions if
`obj is not None`.

#### `authenticate(username=None, password=None, **kwargs)`

Tries to authenticate `username` with `password` by calling
[`User.check_password`](#django.contrib.auth.models.User.check_password). If no `username`
is provided, it tries to fetch a username from `kwargs` using the
key [`CustomUser.USERNAME_FIELD`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD). Returns an
authenticated user or `None`.

#### `get_user_permissions(user_obj, obj=None)`

Returns the set of permission strings the `user_obj` has from their
own user permissions. Returns an empty set if
[`is_anonymous`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser.is_anonymous) or
[`is_active`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.CustomUser.is_active) is `False`.

#### `get_group_permissions(user_obj, obj=None)`

Returns the set of permission strings the `user_obj` has from the
permissions of the groups they belong. Returns an empty set if
[`is_anonymous`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser.is_anonymous) or
[`is_active`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.CustomUser.is_active)  is `False`.

#### `get_all_permissions(user_obj, obj=None)`

Returns the set of permission strings the `user_obj` has, including both
user permissions and group permissions. Returns an empty set if
[`is_anonymous`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser.is_anonymous) or
[`is_active`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.CustomUser.is_active) is `False`.

#### `has_perm(user_obj, perm, obj=None)`

Uses [`get_all_permissions()`](#django.contrib.auth.backends.ModelBackend.get_all_permissions) to check if `user_obj` has the
permission string `perm`. Returns `False` if the user is not
[`is_active`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.CustomUser.is_active).

#### `has_module_perms(self, user_obj, app_label)`

Returns whether the `user_obj` has any permissions on the app
`app_label`.

#### `user_can_authenticate()`

> **New in Django 1.10**

Returns whether the user is allowed to authenticate. To match the
behavior of [`AuthenticationForm`](/ja/1.10/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm)
which [`prohibits inactive users from logging in`](/ja/1.10/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed),
this method returns `False` for users with [`is_active=False`](#django.contrib.auth.models.User.is_active). Custom user models that
don't have an [`is_active`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.CustomUser.is_active)
field are allowed.

#### `class AllowAllUsersModelBackend`

> **New in Django 1.10**

Same as [`ModelBackend`](#django.contrib.auth.backends.ModelBackend) except that it doesn't reject inactive users
because [`user_can_authenticate()`](#django.contrib.auth.backends.ModelBackend.user_can_authenticate) always returns `True`.

When using this backend, you'll likely want to customize the
[`AuthenticationForm`](/ja/1.10/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm) used by the
[`login()`](/ja/1.10/topics/auth/default/#django.contrib.auth.views.login) view by overriding the
[`confirm_login_allowed()`](/ja/1.10/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed)
method as it rejects inactive users.

#### `class RemoteUserBackend`

Use this backend to take advantage of external-to-Django-handled
authentication.  It authenticates using usernames passed in
[`request.META['REMOTE_USER']`](/ja/1.10/ref/request-response/#django.http.HttpRequest.META).  See
the [Authenticating against REMOTE\_USER](/ja/1.10/howto/auth-remote-user/)
documentation.

If you need more control, you can create your own authentication backend
that inherits from this class and override these attributes or methods:

#### `RemoteUserBackend.create_unknown_user`

`True` or `False`. Determines whether or not a user object is created
if not already in the database  Defaults to `True`.

#### `RemoteUserBackend.authenticate(remote_user)`

The username passed as `remote_user` is considered trusted. This method
simply returns the user object with the given username, creating a new
user object if [`create_unknown_user`](#django.contrib.auth.backends.RemoteUserBackend.create_unknown_user) is `True`.

Returns `None` if [`create_unknown_user`](#django.contrib.auth.backends.RemoteUserBackend.create_unknown_user) is
`False` and a `User` object with the given username is not found in the
database.

#### `RemoteUserBackend.clean_username(username)`

Performs any cleaning on the `username` (e.g. stripping LDAP DN
information) prior to using it to get or create a user object. Returns the
cleaned username.

#### `RemoteUserBackend.configure_user(user)`

Configures a newly created user.  This method is called immediately after a
new user is created, and can be used to perform custom setup actions, such
as setting the user's groups based on attributes in an LDAP directory.
Returns the user object.

#### `RemoteUserBackend.user_can_authenticate()`

> **New in Django 1.10**

Returns whether the user is allowed to authenticate. This method returns
`False` for users with [`is_active=False`](#django.contrib.auth.models.User.is_active). Custom user models that don't
have an [`is_active`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.CustomUser.is_active) field are
allowed.

#### `class AllowAllUsersRemoteUserBackend`

> **New in Django 1.10**

Same as [`RemoteUserBackend`](#django.contrib.auth.backends.RemoteUserBackend) except that it doesn't reject inactive
users because [`user_can_authenticate`](#django.contrib.auth.backends.RemoteUserBackend.user_can_authenticate) always
returns `True`.

## Utility functions

#### `get_user(request)`

Returns the user model instance associated with the given `request`’s
session.

It checks if the authentication backend stored in the session is present in
[`AUTHENTICATION_BACKENDS`](/ja/1.10/ref/settings/#std-setting-AUTHENTICATION_BACKENDS). If so, it uses the backend's
`get_user()` method to retrieve the user model instance and then verifies
the session by calling the user model's
[`get_session_auth_hash()`](/ja/1.10/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash)
method.

Returns an instance of [`AnonymousUser`](#django.contrib.auth.models.AnonymousUser)
if the authentication backend stored in the session is no longer in
[`AUTHENTICATION_BACKENDS`](/ja/1.10/ref/settings/#std-setting-AUTHENTICATION_BACKENDS), if a user isn't returned by the
backend's `get_user()` method, or if the session auth hash doesn't
validate.
