---
title: "Django の認証方法のカスタマイズ"
version: 2.0
locale: ja
source: https://docs.djangoproject.com/ja/2.0/topics/auth/customizing/
canonical: https://djangodocs.dev/ja/2.0/topics/auth/customizing/
---
# Django の認証方法のカスタマイズ

The authentication that comes with Django is good enough for most common cases,
but you may have needs not met by the out-of-the-box defaults. Customizing
authentication in your projects requires understanding what points of the
provided system are extensible or replaceable. This document provides details
about how the auth system can be customized.

[認証バックエンド](#authentication-backends) を利用すると、ユーザーモデルに保存されたユーザー名とパスワードを用いて異なるサービス間での認証を行う必要が生じた場合に Django 標準よりも高い拡張性を持たせることができます。

あなたはDjango認証システムを通した認証による改良したパーミッション\<custom-permission\>をあなたのユーザモデルに組み込むことができるでしょう。

あなたは標準の `User` モデルを [拡張](#extending-user)、もしくは完全にカスタマイズしたモデルを [代わりに用いる](#auth-custom-user) 事ができます。

## 他の認証ソースを利用する

もしかしたらあなたは，他の認証元からユーザネームとパスワード，もしくは認証方式のため，別の認証元にhookする必要があるかもしれません。

例えばあなたの会社ですでに全ての従業員のユーザ名とパスワードを記録しているLDAP認証があるとしましょう。もしユーザがLDAP認証とdjangoアプリケーションで異なるアカウントだとしたらネットワーク管理者とユーザで口論になるでしょう。

そこでこのような状況に対応するためにDjangoの認証システムは他の認証システムのリソースと接続できます。あなたはDjangoのデフォルトのデータベーススキーマをオーバーライドするか、他のシステムを連携するためにデフォルトシステムを使うことができます。

Django に含まれている認証バックエンドに関する情報は [認証バックエンドリファレンス](/ja/2.0/ref/contrib/auth/#authentication-backends-reference) を参照してください。

### 認証バックエンドを指定する

内部的に、Django は認証を確認する「認証バックエンド」のリストを保持しています。[`django.contrib.auth.authenticate()`](/ja/2.0/topics/auth/default/#django.contrib.auth.authenticate) を誰かがコールすると -- [どのようにログインするか](/ja/2.0/topics/auth/default/#how-to-log-a-user-in) で記述されているように -- Django はその認証バックエンド全てに対して認証を試行します。最初の認証方法が失敗した場合、Django は次の方法、また次の方法といった具合に、全てのバックエンドに対して認証を試行します。

認証バックエンドとして利用するリストは [`AUTHENTICATION_BACKENDS`](/ja/2.0/ref/settings/#std-setting-AUTHENTICATION_BACKENDS) に定義されています。この設定値は認証方法を定義している Python クラスを指定する Python パスのリスト型変数でなければなりません。これらのクラスはあなたの環境で有効な Python パスのどこにでも配置可能です。

初期状態では、[`AUTHENTICATION_BACKENDS`](/ja/2.0/ref/settings/#std-setting-AUTHENTICATION_BACKENDS) は以下の値として定義されています。:

```
['django.contrib.auth.backends.ModelBackend']
```

これは Django のユーザーデータベースを確認してビルトインの権限を照会する基本的な認証バックエンドです。このバックエンドにはログイン試行を制限することでブルートフォース攻撃を防御する仕組みは提供していません。独自に試行制限を実装した認証バックエンドを利用するか、多くのウェブサーバーで提供されている各種防御機構が利用可能です。

[`AUTHENTICATION_BACKENDS`](/ja/2.0/ref/settings/#std-setting-AUTHENTICATION_BACKENDS) への順番は処理に影響し、同じユーザー名とパスワードによって複数のバックエンドで有効な認証と判定されれば、Django は最初に有効と判定した時点で処理を終了します。

ある認証バックエンドにおいて PermissionDenied 例外が発生した場合、認証処理は直ちに終了し、Django は続く認証バックエンドに対する認証判定を行いません。

> **Note**
>
> あるユーザーが一度認証されると、Django はそのユーザーの有効なセッション中はどの認証バックエンドがそのユーザーの認証に利用されたかを保持し、そのセッション有効期限中は認証されたユーザーの情報にアクセスする必要が生じる毎に同じ認証バックエンドを再利用します。これは認証情報がセッション毎に事実上キャッシュされる事を意味しており、従って [`AUTHENTICATION_BACKENDS`](/ja/2.0/ref/settings/#std-setting-AUTHENTICATION_BACKENDS) を変更すると、ユーザーに対して異なる方法を用いた再認証を要求する際にはセッション情報を破棄する必要が有ります。これを実現する簡単な一つの方法は `Session.objects.all().delete()` をただ利用することです。

### 認証バックエンドの実装

認証バックエンドは2つの必須メソッド: `get_user(user_id)` と `authenticate(request, **credentials)` を持ったクラスであり、 また、パーミッションに関連した省略可能な [authorization methods](#authorization-methods) を持ちます。

`get_user` メソッドは `user_id` -- ユーザー名、データベース上の ID 等何でも利用できますが、あなたが定義したユーザーオブジェクトの主キーである値 -- を取って一つのユーザーオブジェクトを返します。

`authenticate` メソッドは `request` 引数と、キーワード引数として認証情報を持ちます。多くの場合、次のように表されます:

```
class MyBackend:
    def authenticate(self, request, username=None, password=None):
        # Check the username/password and return a user.
        ...
```

一方、次のように認証トークンでも表せます:

```
class MyBackend:
    def authenticate(self, request, token=None):
        # Check the token and return a user.
        ...
```

いずれの場合にせよ、 `authenticate()` は与えられた認証情報を確認し、それが有効であれば、認証情報とマッチしたユーザーオブジェクトを返すべきです。それが有効でなければ `None` を返すべきです。

`request` は [`HttpRequest`](/ja/2.0/ref/request-response/#django.http.HttpRequest) で、  [`authenticate()`](/ja/2.0/topics/auth/default/#django.contrib.auth.authenticate) が提供されていない場合 `None`  となる可能性があります。(バックエンドでこれを通過するため).

Django の admin は Django の [User object](/ja/2.0/topics/auth/default/#user-objects) と強く結合しています。これを扱う最も良い方法は Django の `User` オブジェクトを、あなたのバックエンド（例えば、LDAP ディレクトリ、外部の SQL データベースなど）に存在するそれぞれのユーザーに対して作成することです。これを行うためのスクリプトを事前に記述しておくか、ユーザーが初めてログインするときに `authenticate` メソッドがこれを行えるようにしておくと良いでしょう。

次に示すのが、 `settings.py` で定義されたユーザー名とパスワードの変数に対して認証し、ユーザーの認証が初めてであった場合に Django の `User` オブジェクトを作成するバックエンドの例です:

```
from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User

class SettingsBackend:
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
    """

    def authenticate(self, request, username=None, password=None):
        login_valid = (settings.ADMIN_LOGIN == username)
        pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. There's no need to set a password
                # because only the password from settings.py is checked.
                user = User(username=username)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
```

> **Changed in Django 1.11**
>
> `request` パラメタが `authenticate()` に追加され、これを受け入れていないバックエンドのサポートは Django 2.1. で削除される予定です。

### カスタムバックエンドによる認可の扱い

カスタム認証バックエンドはそれら独自のパーミッションを提供することができます。

ユーザーモデルはパーミッションを取得する関数たち  ([`get_group_permissions()`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.User.get_group_permissions), [`get_all_permissions()`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.User.get_all_permissions), [`has_perm()`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.User.has_perm), and  [`has_module_perms()`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.User.has_module_perms)) の機能を、これらの関数たちを実装した認証バックエンドに委任します。

これによりユーザーに与えられたパーミッションは全てのバックエンドが返すすべてのパーミッションの上位セットになります。つまり、Django はユーザーに、任意のバックエンドが付与するパーミッションを与えます。

もし例外 [`PermissionDenied`](/ja/2.0/ref/exceptions/#django.core.exceptions.PermissionDenied)  を [`has_perm()`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.User.has_perm) か [`has_module_perms()`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.User.has_module_perms) の中でバックエンドが出した場合、認可は直ちに失敗し、 Django はそこから続くバックエンドを確認しません。

上記のシンプルなバックエンドは、魔法の admin のパーミッションを非常に簡潔に実装することができます:

```
class SettingsBackend:
    ...
    def has_perm(self, user_obj, perm, obj=None):
        return user_obj.username == settings.ADMIN_LOGIN
```

上記の例では、アクセスしたユーザーに全てのパーミッションを付与します。注意すべき点として、関数 [`django.contrib.auth.models.User`](/ja/2.0/ref/contrib/auth/#id1)  から関連して得られた同じ引数は、バックエンド認証関数は、匿名のユーザーを表すものも含んでいるかもしれない、全てのユーザーオブジェクトを引数として取る点があります。

認可の実装の完全なものは [django/contrib/auth/backends.py](https://github.com/django/django/blob/master/django/contrib/auth/backends.py) の `ModelBackend` クラスにあり、これはデフォルトのバックエンドであり、ほとんどの場合 `auth_permission` テーブルを照会します。もしバックエンド API の一部だけにカスタムの動作を行わせようとした場合は、カスタムのバックエンド API に完全な API を実装せずとも、Python の継承と `ModelBackend` サブクラスを利用できます。

#### 匿名ユーザーに対する認可

匿名ユーザーは認証されていないユーザー、すなわち有効な認証の詳述を受けていないユーザーです。しかし、それは彼らが何かを行う権限を持っていないことを意味するとは限りません。一般的な話として、多くのウェブサイトは匿名のユーザーにサイトの大部分を閲覧する権限を与え、多くのユーザーにコメント投稿を許可するなどしています。

Django のパーミッションフレームワークは匿名ユーザーのパーミッションを保持する場所を持ちません。しかし、認証バックエンドに渡されるユーザーオブジェクトの1つ、 [`django.contrib.auth.models.AnonymousUser`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.AnonymousUser) オブジェクトは、バックエンドが匿名ユーザーのためのカスタムの認証の動作を指定することを可能とします。これは、たとえば匿名のアクセスをコントロールするといった設定を必要とせず、認証の課題のすべてを認証バックエンドに任せるような、再利用可能なアプリの作者にとって非常に便利です。

#### アクティブでないユーザーに対する認証

[`is_active`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.User.is_active) フィールドが `False` となっているユーザーを、アクティブでないユーザーと呼びます。認証バックエンド [`ModelBackend`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.backends.ModelBackend) と [`RemoteUserBackend`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.backends.RemoteUserBackend) はこれらのユーザーの認証行為を禁止します。カスタムユーザーモデルが [`is_active`](#django.contrib.auth.models.CustomUser.is_active) を持っていない場合、すべてのユーザーの認証行為が許可されます。

もし、アクティブでないユーザーの認証行為を許可したい場合は、[`AllowAllUsersModelBackend`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.backends.AllowAllUsersModelBackend) や [`AllowAllUsersRemoteUserBackend`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.backends.AllowAllUsersRemoteUserBackend) を使用することができます。

パーミッションシステムが匿名ユーザーをサポートしている場合、匿名ユーザーがパーミッションを持つ操作であっても、アクティブでないユーザーにはそれができないということが起こりえます。

バックエンドで独自のパーミッションメソッド持つときは、ユーザーの `is_active` 属性のテストを忘れずに行ってください。

#### オブジェクトのパーミッションの取扱い

Django のパーミッションフレームワークはオブジェクトパーミッション基盤を持っていますが、コアには実装されていません。これにより、オブジェクトパーミッションのチェックは常に `False` または空のリスト（実行されたチェックに応じていずれか）が返されます。認証バックエンドは、オブジェクトに関連した認証メソッドごとに `obj` and `user_obj` のキーワードパラメタを受け取り、必要に応じてオブジェクトレベルのパーミッションを返します。

## カスタムのパーミッション

モデルオブジェクトに対してカスタムパーミッションを作成したい場合は [model Meta attribute](/ja/2.0/topics/db/models/#meta-options) の\`\`permissions\`\` を使用してください。

この例の Task モデルはアプリケーションに固有の3つのカスタムパーミッション、すなわちユーザーが Task インスタンスで実行可能、または不可能なアクションを作成しています:

```
class Task(models.Model):
    ...
    class Meta:
        permissions = (
            ("view_task", "Can see available tasks"),
            ("change_task_status", "Can change the status of tasks"),
            ("close_task", "Can remove a task by setting its status as closed"),
        )
```

これは、[`manage.py migrate`](/ja/2.0/ref/django-admin/#django-admin-migrate) ( [`post_migrate`](/ja/2.0/ref/signals/#django.db.models.signals.post_migrate) シグナルに接続されたパーミッション作成関数) を実行したときに、追加のパーミッションを作成するだけです。ユーザーがアプリケーションによって提供される機能 (task の表示、task の status 変更、task の終了）にアクセスしようとしているときに、これらのアクセスのパーミッションの値をチェックするコードは自身で記述する必要があります。上記の例のようにした場合、ユーザーが task の閲覧を可能かのチェックは次のように記述できます:

```
user.has_perm('app.view_task')
```

## 既存の `User` モデルを拡張する

独自のモデルを使用することなく、デフォルトのモデル [`User`](/ja/2.0/ref/contrib/auth/#id1) を拡張する方法が2つあります。振る舞いのみを変更し、データベースに格納されている内容を変更する必要がない場合は [`User`](/ja/2.0/ref/contrib/auth/#id1) に基づいて [proxy model](/ja/2.0/topics/db/models/#proxy-models)  を作成できます。これにより、デフォルトの並び順、カスタムマネージャ、カスタムモデルメソッドなど、プロキシモデルによって提供される機能を利用可能です。

`User` に関連した情報を格納したい場合は、 [`OneToOneField`](/ja/2.0/ref/models/fields/#django.db.models.OneToOneField) を追加する情報のフィールドを持ったモデルに使用することができます。この1対1モデルはサイトユーザーに関する、認証には関連しない情報を格納することがあるため、しばしばプロファイルモデルと呼ばれます。たとえば、次のような Employee モデルを作ります:

```
from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.CharField(max_length=100)
```

User モデルと Employee モデルの両方を持っている既存の従業員 Fred Smith について、Django の標準の関連モデル規則を使用して関連情報にアクセスできます:

```
>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department
```

admin のユーザーページにプロファイルモデルのフィールドを追加する場合は、[`InlineModelAdmin`](/ja/2.0/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin) (この例では、[`StackedInline`](/ja/2.0/ref/contrib/admin/#django.contrib.admin.StackedInline) を使用しています) をあなたの `admin.py` に定義し、それを [`User`](/ja/2.0/ref/contrib/auth/#id1) クラスで追加した `UserAdmin` クラスに追加します。

```
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User

from my_user_profile_app.models import Employee

# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class EmployeeInline(admin.StackedInline):
    model = Employee
    can_delete = False
    verbose_name_plural = 'employee'

# Define a new User admin
class UserAdmin(BaseUserAdmin):
    inlines = (EmployeeInline, )

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
```

これらのプロファイルモデルは特殊なものではありませんー単純にユーザーモデルと1体1でリンクされた Django モデルです。したがって、ユーザー作成時に自動的に作成されることはありませんが、[`django.db.models.signals.post_save`](/ja/2.0/ref/signals/#django.db.models.signals.post_save) を活用することで関連づけしたモデルを作成、更新することができます。

関連づけされたモデルを使用した場合、関連するデータを検索するための追加のクエリ実行や結合が行われます。あなたの必要性に応じて、関連づけされたフィールドをカスタムユーザーモデルにインクルードすることは適した選択肢となるでしょう。しかしながら、デフォルトのユーザーモデルとプロジェクトのアプリケーションに組み込み済みの連携は追加のデータベース負荷を正当化するでしょう。

## カスタムの `User` モデルを置き換える

Django にビルトインされている [`User`](/ja/2.0/ref/contrib/auth/#id1) モデルは、必ずしもプロジェクトが必要とする認証のモデルと合致するわけではありません。たとえば、サイトによってはユーザー名の代わりにメールアドレスを識別トークンとして使用する方が適した場合があります。

Django では、カスタムモデルを参照するように  [`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL) の値を設定することにより、デフォルトのユーザーモデルをオーバーライドすることができます:

```
AUTH_USER_MODEL = 'myapp.MyUser'
```

このドットで区切られたペアは Django app の名前 ( [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS) に含まれている必要があります) とあなたがユーザーモデルとして使用したい Django モデルの名前です。

### プロジェクトの開始時にカスタムのユーザーモデルを使用する

新しくプロジェクトを始める場合は、デフォルトの [`User`](/ja/2.0/ref/contrib/auth/#id1) で十分である場合でも、カスタムユーザーモデルを作成することを強く推奨します。このモデルはデフォルトのユーザーモデルと同様に動作しますが、必要に応じて将来的にカスタマイズすることができます:

```
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass
```

[`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL) に指定することを忘れないでください。任意のマイグレーションの作成、また、最初に実行する `manage.py migrate` の前に行ってください。

そして、モデルをアプリの `admin.py` に登録してください:

```
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User

admin.site.register(User, UserAdmin)
```

### プロジェクト途中からのカスタムユーザーモデルへの変更

[`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL) をデータベーステーブルの作成後に変更することは、たとえば、外部キーや多対多の関係に影響するため、非常に困難となります。

この変更は自動的には行うことができません。手動でのスキーマ修正、古いユーザーテーブルからのデータ移動、一部のマイグレーションの手動による再適用をする必要があります。ステップの概要は [#25313](https://code.djangoproject.com/ticket/25313) を参照してください。

スワップ可能なモデルという Django の動的依存性により、 [`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL) によって参照されるモデルはアプリの初回のマイグレーションで作成されなければなりません（通常は `0001_initial` と呼ばれます）。そうしない場合、依存関係の問題が発生します。

In addition, you may run into a `CircularDependencyError` when running your
migrations as Django won't be able to automatically break the dependency loop
due to the dynamic dependency. If you see this error, you should break the loop
by moving the models depended on by your user model into a second migration.
(You can try making two normal models that have a `ForeignKey` to each other
and seeing how `makemigrations` resolves that circular dependency if you want
to see how it's usually done.)

### 再利用可能なアプリと `AUTH_USER_MODEL`

Reusable apps shouldn't implement a custom user model. A project may use many
apps, and two reusable apps that implemented a custom user model couldn't be
used together. If you need to store per user information in your app, use
a [`ForeignKey`](/ja/2.0/ref/models/fields/#django.db.models.ForeignKey) or
[`OneToOneField`](/ja/2.0/ref/models/fields/#django.db.models.OneToOneField) to `settings.AUTH_USER_MODEL`
as described below.

### `User` モデルを参照する

[`User`](/ja/2.0/ref/contrib/auth/#id1) を直接参照する場合 (例えば外部キーで参照する場合)、[`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL) 設定が異なるユーザモデルに変更されたプロジェクトでは正しく動作しません。

#### `get_user_model()`

[`User`](/ja/2.0/ref/contrib/auth/#id1) を直接参照する代わりに、`django.contrib.auth.get_user_model()` を使ってユーザモデルを参照すべきです。このメソッドは現在アクティブなユーザモデルを返します -- 指定されている場合はカスタムのユーザモデル、指定されていない場合は [`User`](/ja/2.0/ref/contrib/auth/#id1) です。

ユーザモデルに対して外部キーや多対多の関係を定義するときは、[`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL) 設定を使ってカスタムのモデルを指定してください。例えば:

```
from django.conf import settings
from django.db import models

class Article(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
```

ユーザモデルによって送信されたシグナルと接続するときは、[`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL) 設定を使ってカスタムのユーザモデルを指定してください。例えば:

```
from django.conf import settings
from django.db.models.signals import post_save

def post_save_receiver(sender, instance, created, **kwargs):
    pass

post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
```

Generally speaking, it's easiest to refer to the user model with the
[`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL) setting in code that's executed at import time,
however, it's also possible to call `get_user_model()` while Django
is importing models, so you could use
`models.ForeignKey(get_user_model(), ...)`.

If your app is tested with multiple user models, using
`@override_settings(AUTH_USER_MODEL=...)` for example, and you cache the
result of `get_user_model()` in a module-level variable, you may need to
listen to the  [`setting_changed`](/ja/2.0/ref/signals/#django.test.signals.setting_changed) signal to clear
the cache. For example:

```
from django.apps import apps
from django.contrib.auth import get_user_model
from django.core.signals import setting_changed
from django.dispatch import receiver

@receiver(setting_changed)
def user_model_swapped(**kwargs):
    if kwargs['setting'] == 'AUTH_USER_MODEL':
        apps.clear_cache()
        from myapp import some_module
        some_module.UserModel = get_user_model()
```

> **Changed in Django 1.11**
>
> import時に\`\`get\_user\_model()\`\`を呼び出す機能が追加されました。

### カスタムのユーザーモデルを指定する

> **モデルの設計について考慮すべきこと**
>
> カスタムのユーザーモデルで認証に直接関係する情報を取り扱う前には、よく考慮する必要があります。
>
> It may be better to store app-specific user information in a model
> that has a relation with the user model. That allows each app to specify
> its own user data requirements without risking conflicts with other
> apps. On the other hand, queries to retrieve this related information
> will involve a database join, which may have an effect on performance.

Django は、カスタムのユーザーモデルがいくつかの最低限の要件を満たしていることを期待します。

デフォルトの認証バックエンドを使用している場合、モデルは必ず、認証のために使用できるユニークなフィールドを1つ持たなければなりません。このフィールドとしては、ユーザー名やメールアドレスなど、ユニークな属性ならば使用できます。ユニークでないユーザー名などのフィールドが使用できるのは、そのようなフィールドを扱えるカスタムの認証バックエンドだけです。

The easiest way to construct a compliant custom user model is to inherit from
[`AbstractBaseUser`](#django.contrib.auth.models.AbstractBaseUser).
[`AbstractBaseUser`](#django.contrib.auth.models.AbstractBaseUser) provides the core
implementation of a user model, including hashed passwords and tokenized
password resets. You must then provide some key implementation details:

#### `class models.CustomUser`

#### `USERNAME_FIELD`

A string describing the name of the field on the user model that is
used as the unique identifier. This will usually be a username of some
kind, but it can also be an email address, or any other unique
identifier. The field *must* be unique (i.e., have `unique=True` set
in its definition), unless you use a custom authentication backend that
can support non-unique usernames.

以下の例では、フィールドを一意に指定するために、`identifier` フィールドが使われています。

```
class MyUser(AbstractBaseUser):
    identifier = models.CharField(max_length=40, unique=True)
    ...
    USERNAME_FIELD = 'identifier'
```

[`USERNAME_FIELD`](#django.contrib.auth.models.CustomUser.USERNAME_FIELD) now supports
[`ForeignKey`](/ja/2.0/ref/models/fields/#django.db.models.ForeignKey)s. Since there is no way to pass
model instances during the [`createsuperuser`](/ja/2.0/ref/django-admin/#django-admin-createsuperuser) prompt, expect the
user to enter the value of [`to_field`](/ja/2.0/ref/models/fields/#django.db.models.ForeignKey.to_field)
value (the [`primary_key`](/ja/2.0/ref/models/fields/#django.db.models.Field.primary_key) by default) of an
existing instance.

#### `EMAIL_FIELD`

> **New in Django 1.11**

A string describing the name of the email field on the `User` model.
This value is returned by
[`get_email_field_name()`](#django.contrib.auth.models.AbstractBaseUser.get_email_field_name).

#### `REQUIRED_FIELDS`

A list of the field names that will be prompted for when creating a
user via the [`createsuperuser`](/ja/2.0/ref/django-admin/#django-admin-createsuperuser) management command. The user
will be prompted to supply a value for each of these fields. It must
include any field for which [`blank`](/ja/2.0/ref/models/fields/#django.db.models.Field.blank) is
`False` or undefined and may include additional fields you want
prompted for when a user is created interactively.
`REQUIRED_FIELDS` has no effect in other parts of Django, like
creating a user in the admin.

For example, here is the partial definition for a user model that
defines two required fields - a date of birth and height:

```
class MyUser(AbstractBaseUser):
    ...
    date_of_birth = models.DateField()
    height = models.FloatField()
    ...
    REQUIRED_FIELDS = ['date_of_birth', 'height']
```

> **Note**
>
> `REQUIRED_FIELDS` must contain all required fields on your user
> model, but should *not* contain the `USERNAME_FIELD` or
> `password` as these fields will always be prompted for.

[`REQUIRED_FIELDS`](#django.contrib.auth.models.CustomUser.REQUIRED_FIELDS) now supports
[`ForeignKey`](/ja/2.0/ref/models/fields/#django.db.models.ForeignKey)s. Since there is no way to pass
model instances during the [`createsuperuser`](/ja/2.0/ref/django-admin/#django-admin-createsuperuser) prompt, expect the
user to enter the value of [`to_field`](/ja/2.0/ref/models/fields/#django.db.models.ForeignKey.to_field)
value (the [`primary_key`](/ja/2.0/ref/models/fields/#django.db.models.Field.primary_key) by default) of an
existing instance.

#### `is_active`

A boolean attribute that indicates whether the user is considered
"active".  This attribute is provided as an attribute on
`AbstractBaseUser` defaulting to `True`. How you choose to
implement it will depend on the details of your chosen auth backends.
See the documentation of the [`is_active attribute on the built-in
user model`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.User.is_active) for details.

#### `get_full_name()`

Optional. A longer formal identifier for the user such as their full
name. If implemented, this appears alongside the username in an
object's history in [`django.contrib.admin`](/ja/2.0/ref/contrib/admin/#module-django.contrib.admin).

#### `get_short_name()`

Optional. A short, informal identifier for the user such as their
first name. If implemented, this replaces the username in the greeting
to the user in the header of [`django.contrib.admin`](/ja/2.0/ref/contrib/admin/#module-django.contrib.admin).

> **Changed in Django 2.0**
>
> In older versions, subclasses are required to implement
> `get_short_name()` and `get_full_name()` as `AbstractBaseUser`
> has implementations that raise `NotImplementedError`.

> **AbstractBaseUser のインポート**
>
> `AbstractBaseUser` と `BaseUserManager` は `django.contrib.auth.base_user` からインポートでき、 [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS) の中に `django.contrib.auth` をインクルードすることなくインポートできます。

次の属性とメソッドは  [`AbstractBaseUser`](#django.contrib.auth.models.AbstractBaseUser): の任意のサブクラスで利用可能です。

#### `class models.AbstractBaseUser`

#### `get_username()`

`USERNAME_FIELD` で指定されたフィールドの値を返します。

#### `clean()`

[`normalize_username()`](#django.contrib.auth.models.AbstractBaseUser.normalize_username) を呼び出し、username を正規化します。このメソッドをオーバーライドした場合、正規化を保持するために `super()` を呼び出すようにしてください。

#### `classmethod get_email_field_name()`

> **New in Django 1.11**

[`EMAIL_FIELD`](#django.contrib.auth.models.CustomUser.EMAIL_FIELD) 属性で指定されたメールフィールドの名前を返します。`EMAIL_FIELD` の指定が無いとき、デフォルトは `'email'` です。

#### `classmethod normalize_username(username)`

視覚的に同一であるが異なる Unicode の符号位置を持つ文字について、それらが同一とみなされるように、username に NFKC Unicode正規化を適用します。

#### `is_authenticated`

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

#### `is_anonymous`

Read-only attribute which is always `False`. This is a way of
differentiating [`User`](/ja/2.0/ref/contrib/auth/#id1) and [`AnonymousUser`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.AnonymousUser)
objects. Generally, you should prefer using
[`is_authenticated`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated) to this attribute.

#### `set_password(raw_password)`

Sets the user's password to the given raw string, taking care of the
password hashing. Doesn't save the
[`AbstractBaseUser`](#django.contrib.auth.models.AbstractBaseUser) object.

When the raw\_password is `None`, the password will be set to an
unusable password, as if
[`set_unusable_password()`](#django.contrib.auth.models.AbstractBaseUser.set_unusable_password)
were used.

#### `check_password(raw_password)`

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

#### `set_unusable_password()`

Marks the user as having no password set.  This isn't the same as
having a blank string for a password.
[`check_password()`](#django.contrib.auth.models.AbstractBaseUser.check_password) for this user
will never return `True`. Doesn't save the
[`AbstractBaseUser`](#django.contrib.auth.models.AbstractBaseUser) object.

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

#### `has_usable_password()`

Returns `False` if
[`set_unusable_password()`](#django.contrib.auth.models.AbstractBaseUser.set_unusable_password) has
been called for this user.

#### `get_session_auth_hash()`

Returns an HMAC of the password field. Used for
[Session invalidation on password change](/ja/2.0/topics/auth/default/#session-invalidation-on-password-change).

[`AbstractUser`](#django.contrib.auth.models.AbstractUser) subclasses [`AbstractBaseUser`](#django.contrib.auth.models.AbstractBaseUser):

#### `class models.AbstractUser`

#### `clean()`

> **New in Django 1.11**

Normalizes the email by calling
[`BaseUserManager.normalize_email()`](#django.contrib.auth.models.BaseUserManager.normalize_email). If you override this method,
be sure to call `super()` to retain the normalization.

You should also define a custom manager for your user model. If your user model
defines `username`, `email`, `is_staff`, `is_active`, `is_superuser`,
`last_login`, and `date_joined` fields the same as Django's default user,
you can just install Django's [`UserManager`](/ja/2.0/ref/contrib/auth/#django.contrib.auth.models.UserManager);
however, if your user model defines different fields, you'll need to define a
custom manager that extends [`BaseUserManager`](#django.contrib.auth.models.BaseUserManager)
providing two additional methods:

#### `class models.CustomUserManager`

#### `create_user(*username_field*, password=None, \**other_fields)`

The prototype of `create_user()` should accept the username field,
plus all required fields as arguments. For example, if your user model
uses `email` as the username field, and has `date_of_birth` as a
required field, then `create_user` should be defined as:

```
def create_user(self, email, date_of_birth, password=None):
    # create user here
    ...
```

#### `create_superuser(*username_field*, password, \**other_fields)`

The prototype of `create_superuser()` should accept the username
field, plus all required fields as arguments. For example, if your user
model uses `email` as the username field, and has `date_of_birth`
as a required field, then `create_superuser` should be defined as:

```
def create_superuser(self, email, date_of_birth, password):
    # create superuser here
    ...
```

Unlike `create_user()`, `create_superuser()` *must* require the
caller to provide a password.

[`BaseUserManager`](#django.contrib.auth.models.BaseUserManager) provides the following
utility methods:

#### `class models.BaseUserManager`

#### `classmethod normalize_email(email)`

Normalizes email addresses by lowercasing the domain portion of the
email address.

#### `get_by_natural_key(username)`

Retrieves a user instance using the contents of the field
nominated by `USERNAME_FIELD`.

#### `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` (lowercase letter o, uppercase letter o,
  and zero)

### Extending Django's default `User`

If you're entirely happy with Django's [`User`](/ja/2.0/ref/contrib/auth/#id1)
model and you just want to add some additional profile information, you could
simply subclass [`django.contrib.auth.models.AbstractUser`](#django.contrib.auth.models.AbstractUser) and add your
custom profile fields, although we'd recommend a separate model as described in
the "Model design considerations" note of [カスタムのユーザーモデルを指定する](#specifying-custom-user-model).
`AbstractUser` provides the full implementation of the default
[`User`](/ja/2.0/ref/contrib/auth/#id1) as an [abstract model](/ja/2.0/topics/db/models/#abstract-base-classes).

### カスタムのユーザーとビルトインの認証フォーム

Django のビルトインの [forms](/ja/2.0/topics/auth/default/#built-in-auth-forms) と [views](/ja/2.0/topics/auth/default/#built-in-auth-views) は、協調して動作するユーザーモデルに対して、いくつかの前提を置いています。

以下のフォームは [`AbstractBaseUser`](#django.contrib.auth.models.AbstractBaseUser) のあらゆるサブクラスに互換性があります。

- [`AuthenticationForm`](/ja/2.0/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm): [`USERNAME_FIELD`](#django.contrib.auth.models.CustomUser.USERNAME_FIELD) で指定したユーザー名フィールドを使用する。
- [`SetPasswordForm`](/ja/2.0/topics/auth/default/#django.contrib.auth.forms.SetPasswordForm)
- [`PasswordChangeForm`](/ja/2.0/topics/auth/default/#django.contrib.auth.forms.PasswordChangeForm)
- [`AdminPasswordChangeForm`](/ja/2.0/topics/auth/default/#django.contrib.auth.forms.AdminPasswordChangeForm)

以下のフォームは、ユーザーモデルについて以下のようないくつか前提を置いています。これらの前提を満たしている場合、同じユーザーモデルとみなして使用することができます。

- [`PasswordResetForm`](/ja/2.0/topics/auth/default/#django.contrib.auth.forms.PasswordResetForm): Assumes that the user
  model has a field that stores the user's email address with the name returned
  by [`get_email_field_name()`](#django.contrib.auth.models.AbstractBaseUser.get_email_field_name) (`email` by
  default) that can be used to identify the user and a boolean field named
  `is_active` to prevent password resets for inactive users.

最後に、以下のフォームは、[`User`](/ja/2.0/ref/contrib/auth/#id1) と固く結びついているため、カスタムのユーザーモデルとともに使用するには、書き換えや拡張が必要になります。

- [`UserCreationForm`](/ja/2.0/topics/auth/default/#django.contrib.auth.forms.UserCreationForm)
- [`UserChangeForm`](/ja/2.0/topics/auth/default/#django.contrib.auth.forms.UserChangeForm)

If your custom user model is a simple subclass of `AbstractUser`, then you
can extend these forms in this manner:

```
from django.contrib.auth.forms import UserCreationForm
from myapp.models import CustomUser

class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('custom_field',)
```

### カスタムのユーザーと [`django.contrib.admin`](/ja/2.0/ref/contrib/admin/#module-django.contrib.admin)

カスタムのユーザーモデルを admin で動作させたい場合、ユーザーモデルにいくつかの追加の属性とメソッドを定義しなければなりません。これらのメソッドを定義することで、admin はユーザーへアクセスを制御して admin のコンテンツに合わせることができます。

#### `class models.CustomUser`

#### `is_staff`

ユーザーが admin サイトへのアクセス権を持っている時、`True` を返します。

#### `is_active`

ユーザーアカウントが現在アクティブな時、`True` を返します。

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

Returns `True` if the user has the named permission. If `obj` is
provided, the permission needs to be checked against a specific object
instance.

#### `has_module_perms(app_label):`

Returns `True` if the user has permission to access models in
the given app.

You will also need to register your custom user model with the admin. If
your custom user model extends `django.contrib.auth.models.AbstractUser`,
you can use Django's existing `django.contrib.auth.admin.UserAdmin`
class. However, if your user model extends
[`AbstractBaseUser`](#django.contrib.auth.models.AbstractBaseUser), you'll need to define
a custom `ModelAdmin` class. It may be possible to subclass the default
`django.contrib.auth.admin.UserAdmin`; however, you'll need to
override any of the definitions that refer to fields on
`django.contrib.auth.models.AbstractUser` that aren't on your
custom user class.

### カスタムのユーザーとパーミッション

Django のパーミッションフレームワークをカスタムのユーザーモデルに簡単に取り入れられるように用意されているのが、Django の [`PermissionsMixin`](#django.contrib.auth.models.PermissionsMixin) です。これはユーザーモデルの階層に取り入れることができる抽象モデルで、Django のパーミッションモデルをサポートするのに必要なすべてのメソッドとデーターベースのフィールドを使えるようにしてくれます。

[`PermissionsMixin`](#django.contrib.auth.models.PermissionsMixin) は、以下のメソッドと属性を提供します。

#### `class models.PermissionsMixin`

#### `is_superuser`

真偽値です。明示的に与えられない場合でも、ユーザーがが全てのパーミッションを持っているかどうかを示します。

#### `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/2.0/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` を返します。

> **PermissionsMixin と ModelBackend**
>
> If you don't include the
> [`PermissionsMixin`](#django.contrib.auth.models.PermissionsMixin), you must ensure you
> don't invoke the permissions methods on `ModelBackend`. `ModelBackend`
> assumes that certain fields are available on your user model. If your user
> model doesn't provide  those fields, you'll receive database errors when
> you check permissions.

### カスタムのユーザーと proxy モデル

One limitation of custom user models is that installing a custom user model
will break any proxy model extending [`User`](/ja/2.0/ref/contrib/auth/#id1).
Proxy models must be based on a concrete base class; by defining a custom user
model, you remove the ability of Django to reliably identify the base class.

If your project uses proxy models, you must either modify the proxy to extend
the user model that's in use in your project, or merge your proxy's behavior
into your [`User`](/ja/2.0/ref/contrib/auth/#id1) subclass.

### 完全な具体例

Here is an example of an admin-compliant custom user app. This user model uses
an email address as the username, and has a required date of birth; it
provides no permission checking, beyond a simple `admin` flag on the user
account. This model would be compatible with all the built-in auth forms and
views, except for the user creation forms. This example illustrates how most of
the components work together, but is not intended to be copied directly into
projects for production use.

This code would all live in a `models.py` file for a custom
authentication app:

```
from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            date_of_birth=date_of_birth,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, date_of_birth, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            date_of_birth=date_of_birth,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin
```

Then, to register this custom user model with Django's admin, the following
code would be required in the app's `admin.py` file:

```
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from customauth.models import MyUser

class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = MyUser
        fields = ('email', 'date_of_birth')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = MyUser
        fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'date_of_birth', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('date_of_birth',)}),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'date_of_birth', 'password1', 'password2')}
        ),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

# Now register the new UserAdmin...
admin.site.register(MyUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
```

Finally, specify the custom model as the default user model for your project
using the [`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL) setting in your `settings.py`:

```
AUTH_USER_MODEL = 'customauth.MyUser'
```
