次のバージョンとコードスニペットを使用して、プロジェクトに新しい認証バックエンドを追加しようとしています。
django:2.2.1 python:3.5.2 mysql-server:5.7
...
AUTHENTICATION_BACKENDS = ['common.backends.MyOwnAuthenticationBackend']
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class MyOwnAuthenticationBackend(ModelBackend):
print('MOAB')
def authenticate(self, username=None, password=None):
print('AUTH')
...
def get_user(self, username):
print('GETUSER')
try:
return User.objects.get(pk=username)
except User.DoesNotExist:
return None
ログインしようとすると、MOABが返されますが、AUTH文字列またはGETUSER文字列が返されません。
その理由は何でしょうか?
メインのurls.pyには、認証用に次のものが含まれています。
from common import views as common_views
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views
from django.urls import path
...
url(r'^accounts/login/$', views.LoginView, name='auth_login'),
...
私は何を取りこぼしたか?インターネットでたくさんの質問や投稿を読んでいますが、authenticate()メソッドがまったく呼び出されない理由がわかりません。
メソッドは次のようになります。
def authenticate(self, request, username=None, password=None):
認証システムのソースをauthenticate
調べることで、メソッドの署名に必要なパラメーターを確認できます。最初に配置されたパラメーターはrequest
で、次に資格情報が名前付きパラメーターとして解凍されます。
def authenticate(request=None, **credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend, backend_path in _get_backends(return_tuples=True):
try:
inspect.getcallargs(backend.authenticate, request, **credentials)
except TypeError:
# This backend doesn't accept these credentials as arguments. Try the next one.
continue
try:
user = backend.authenticate(request, **credentials)
[...]
(_get_backends
settings.AUTHENTICATION_BACKENDS内のすべてのバックエンドのリストを表します)
カスタム認証に関するドキュメント:https:
//docs.djangoproject.com/en/dev/topics/auth/customizing/#writing-an-authentication-backend
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加