一. API VIEW auth接收请求流程梳理:
1.1 主要流程
APIView.as_view ==> APIView.dispatch ==> APIView.initial ==> APIView.perform_authentication ==> Request.user ==> Request._authenticate ==> Request.authenticator.authenticate(self) ==>
api_settings.DEFAULT_AUTHENTICATION_CLASSES
setting中配置(不配置则使用默认类):api_settings.DEFAULT_AUTHENTICATION_CLASSES:
常用有(也可文字定义):
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
1.2 按上面流程继续走:选择JSONWebTokenAuthentication验证方式:
JSONWebTokenAuthentication.authenticate ==> BaseJSONWebTokenAuthentication.authenticate ==> jwt_decode_handler(jwt_value) ==> api_settings.JWT_DECODE_HANDLER
api_settings.JWT_DECODE_HANDLER (在setting中配置,不配置则使用默认类)
默认:
rest_framework_jwt.utils.jwt_decode_handler ==》jwt.decode
变量:api_settings(rest_framework_jwt.settings.api_setting)
rest_framework_jwt.settings文件中可看到api_settings初始化的默认变量,函数等值
二.主要函数:
2.1 dispatch函数:将request对象初始化为restframework request对象 ==》 initial中进行DRF的三个认证: 登录状态/权限/频率 认证 ==》根据http 请求方法 分配到不同的函数执行
def dispatch(self, request, *args, **kwargs): #APIView.dispatch
"""
`.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 = self.initialize_request(request, *args, **kwargs) #构建restframework.request.Request对象
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
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
2.2 initial函数:进行DRF的三个认证: 登录状态/权限/频率 认证
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.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
# Ensure that the incoming request is permitted
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)
2.3 JSONWebTokenAuthentication.authenticate
self.perform_authentication(request) ==》Request.user ==> Request._authenticate ==> 常用验证方法(如:JSONWebTokenAuthentication.authenticate)
class BaseJSONWebTokenAuthentication(BaseAuthentication):
"""
Token based authentication using the JSON Web Token standard.
"""
def authenticate(self, request):
"""
Returns a two-tuple of `User` and token if a valid signature has been
supplied using JWT-based authentication. Otherwise returns `None`.
"""
jwt_value = self.get_jwt_value(request)
if jwt_value is None:
return None
try:
payload = jwt_decode_handler(jwt_value) #验证方法对token进行验证
except jwt.ExpiredSignature:
msg = _('Signature has expired.')
raise exceptions.AuthenticationFailed(msg)
except jwt.DecodeError:
msg = _('Error decoding signature.')
raise exceptions.AuthenticationFailed(msg)
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed()
user = self.authenticate_credentials(payload)
return (user, jwt_value)
2.4 jwt_decode_handler==》restframework_jwt.utils.iwt_decode_handler==>jwt.decode
def jwt_decode_handler(token):
options = {
'verify_exp': api_settings.JWT_VERIFY_EXPIRATION,
}
# get user from token, BEFORE verification, to get user secret key
unverified_payload = jwt.decode(token, None, False)
secret_key = jwt_get_secret_key(unverified_payload)
return jwt.decode(
token,
api_settings.JWT_PUBLIC_KEY or secret_key,
api_settings.JWT_VERIFY,
options=options,
leeway=api_settings.JWT_LEEWAY,
audience=api_settings.JWT_AUDIENCE,
issuer=api_settings.JWT_ISSUER,
algorithms=[api_settings.JWT_ALGORITHM]
)