restful framework 認證源碼流程

 

Django-Rest-Framework源碼流程

請求到來以後,都要先執行dispatch方法,dispatch方法方法根據請求方式的不一樣觸發get/post/put/delete等方法api

注意:APIView中的dispatch方法有不少功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def dispatch(self, request, *args, **kwargs):
"""
`.dispatch()` is pretty much the same as Django's regular dispatch,
but with extra hooks for startup, finalize, and exception handling.
"""
self.args = args
self.kwargs = kwargs
第一步:對request進行加工(添加數據)
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?

try:
#第二步:
#處理版權信息
#認證
#權限
#請求用戶進行訪問頻率的限制
self.initial(request, *args, **kwargs)

# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed

# 第三步、執行:get/post/put/delete函數
response = handler(request, *args, **kwargs)

except Exception as exc:
response = self.handle_exception(exc)

#第四步、 對返回結果再次進行加工
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response

上面是大體步驟,下面咱們來具體分析一下,看每一個步驟中都具體幹了什麼事restful

對request進行加工(添加數據)

咱們看看request裏面都添加了那些數據app

a

首先  request = self.initialize_request(request, *args, **kwargs)

點進去,會發現:在Request裏面多加了四個,以下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def initialize_request(self, request, *args, **kwargs):
"""
Returns the initial request object.
"""
#吧請求弄成一個字典返回了
parser_context = self.get_parser_context(request)

return Request(
request,
parsers=self.get_parsers(), #解析數據,默認的有三種方式,可點進去看
#self.get_authenticator優先找本身的,沒有就找父類的
authenticators=self.get_authenticators(), #獲取認證相關的全部類並實例化,傳入request對象供Request使用
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)

b

獲取認證相關的類的具體   
authenticators=self.get_authenticators()
1
2
3
4
5
6
def get_authenticators(self):
"""
Instantiates and returns the list of authenticators that this view can use.
"""
#返回的是對象列表
return [auth() for auth in self.authentication_classes] #[SessionAuthentication,BaseAuthentication]

c

查看認證的類:self.authentication_classes
1
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES  #默認的,若是本身有會優先執行本身的

d

接着走進api_settings
1
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS) #點擊繼承的DEFAULTS類
1
2
3
4
5
6
DEFAULTS = {
# Base API policies
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication', #這時候就找到了他默認認證的類了,能夠導入看看
'rest_framework.authentication.BasicAuthentication'
),

e

導入了類看看類裏面具體幹了什麼
1
2
from rest_framework.authentication import SessionAuthentication
from rest_framework.authentication import BaseAuthentication

f

看到裏面有個authenticate方法和authenticate_header方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

class BaseAuthentication(object):
"""
All authentication classes should extend BaseAuthentication.
"""

def authenticate(self, request):
"""
Authenticate the request and return a two-tuple of (user, token).
"""
raise NotImplementedError(".authenticate() must be overridden.")

def authenticate_header(self, request):
"""
Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses.
"""
pass

具體處理認證,從headers裏面能獲取用戶名和密碼ide

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class BasicAuthentication(BaseAuthentication):
"""
HTTP Basic authentication against username/password.
"""
www_authenticate_realm = 'api'

def authenticate(self, request):
"""
Returns a `User` if a correct username and password have been supplied
using HTTP Basic authentication. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()

if not auth or auth[0].lower() != b'basic':
return None #返回none不處理。讓下一個處理

if len(auth) == 1:
msg = _('Invalid basic header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid basic header. Credentials string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)

try:
auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':') #用partition切割冒號也包括
except (TypeError, UnicodeDecodeError, binascii.Error):
msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
raise exceptions.AuthenticationFailed(msg)

userid, password = auth_parts[0], auth_parts[2] # 返回用戶和密碼
return self.authenticate_credentials(userid, password, request)

def authenticate_credentials(self, userid, password, request=None):
"""
Authenticate the userid and password against username and password
with optional request for context.
"""
credentials = {
get_user_model().USERNAME_FIELD: userid,
'password': password
}
user = authenticate(request=request, **credentials)

if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password.'))

if not user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))

return (user, None)

def authenticate_header(self, request):
return 'Basic realm="%s"' % self.www_authenticate_realm

g

固然restfulframework默認定義了兩個類。咱們也能夠自定製類,
本身有就用本身的了,本身沒有就去找父類的了,
可是裏面必須實現authenticate方法,否則會報錯。

進行如下操做

  • 處理版權信息
  • 認證
  • 權限
  • 請求用戶進行訪問頻率的限制

咱們主要來看一下認證流程:函數

a

首先 self.initial(request, *args, **kwargs)能夠看到作了如下操做
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)

# Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg

# Determine the API version, if versioning is in use.
#2.1 處理版本信息
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme

# Ensure that the incoming request is permitted
#2.2 認證
self.perform_authentication(request)
# 2.3 權限
self.check_permissions(request)
# 2.4 請求用戶進行訪問頻率的限制
self.check_throttles(request)

b

咱們先來看認證,self.perform_authentication(request) 
具體幹了什麼,按住ctrl點擊進去
1
2
3
4
5
6
7
8
9
def perform_authentication(self, request):
"""
Perform authentication on the incoming request.

Note that if you override this and simply 'pass', then authentication
will instead be performed lazily, the first time either
`request.user` or `request.auth` is accessed.
"""
request.user #執行request的user,這是的request已是加工後的request了

c

那麼咱們能夠從視圖裏面導入一下Request,找到request對象的user方法
1
from rest_framework.views import Request
1
2
3
4
5
6
7
8
9
10
@property
def user(self):
"""
Returns the user associated with the current request, as authenticated
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate() #
return self._user #返回user

d

執行self._authenticate() 開始用戶認證,
若是驗證成功後返回元組: (用戶,用戶Token)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
"""
#循環對象列表
for authenticator in self.authenticators:
try:
#執行每個對象的authenticate 方法
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise

if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple #返回一個元組,user,和auth,賦給了self,
# 只要實例化Request,就會有一個request對象,就能夠request.user,request.auth了
return

self._not_authenticated()

e

在user_auth_tuple = authenticator.authenticate(self) 進行驗證,
若是驗證成功,執行類裏的authenticatie方法

f

若是用戶沒有認證成功:self._not_authenticated()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def _not_authenticated(self):
"""
Set authenticator, user & authtoken representing an unauthenticated request.

Defaults are None, AnonymousUser & None.
"""
#若是跳過了全部認證,默認用戶和Token和使用配置文件進行設置
self._authenticator = None #

if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER() # 默認值爲:匿名用戶AnonymousUser
else:
self.user = None # None 表示跳過該認證

if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN() # 默認值爲:None
else:
self.auth = None

# (user, token)
# 表示驗證經過並設置用戶名和Token;
# AuthenticationFailed異常

執行get/post/delete等方法

對返回結果在進行加工

相關文章
相關標籤/搜索