<p><strong>如何在DRF中实现自定义身份验证方案?</strong></p>
<p>要实现自定义身份验证方案,我们需要对DRF的<code>BaseAuthentication</code>类进行子类化并重写<code>.authenticate(self, request)</code>方法。</p>
<p>如果身份验证成功,该方法应返回两个元组<code>(user, auth)</code>,否则返回<code>None</code>。在某些情况下,我们可能会从<code>.authenticate()</code>方法引发<code>AuthenticationFailed</code>异常。</p>
<p><strong>示例(来自<a href="http://www.django-rest-framework.org/api-guide/authentication/#example" rel="noreferrer">DRF docs</a>):</strong></p>
<p>假设我们要将任何传入请求验证为名为<code>'X_USERNAME'</code>的自定义请求头中<code>username</code>给定的用户。</p>
<p><strong>步骤1:创建自定义身份验证类</p>
<p>为此,我们将在<code>my_app</code>中创建一个<code>authentication.py</code>文件。</p>
<pre><code># my_app/authentication.py
from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions
class ExampleAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
username = request.META.get('X_USERNAME') # get the username request header
if not username: # no username passed in request headers
return None # authentication did not succeed
try:
user = User.objects.get(username=username) # get the user
except User.DoesNotExist:
raise exceptions.AuthenticationFailed('No such user') # raise exception if user does not exist
return (user, None) # authentication successful
</code></pre>
<p><strong>步骤2:指定自定义身份验证类</p>
<p>创建自定义身份验证类之后,我们需要在DRF设置中定义该身份验证类。这样,所有请求都将基于此身份验证方案进行身份验证。</p>
<pre><code>'DEFAULT_AUTHENTICATION_CLASSES': (
'my_app.authentication.ExampleAuthentication', # custom authentication class
...
),
</code></pre>
<p><strong>注意:</strong>如果要在每个视图或每个视图集的基础上而不是在全局级别上使用此自定义身份验证类,则可以在视图中显式定义此身份验证类。</p>
<pre><code>class MyView(APIView):
authentication_classes = (ExampleAuthentication,) # specify this authentication class in your view
...
</code></pre>