token参考:Django Restful Framework【第三篇】认证、权限、限制访问频率
一、认证
认证请求头
|
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
#!/usr/bin/env python# -*- coding:utf-8 -*-from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.authentication import BaseAuthenticationfrom rest_framework.permissions import BasePermissionfrom rest_framework.request import Requestfrom rest_framework import exceptionstoken_list = [ 'sfsfss123kuf3j123', 'asijnfowerkkf9812',]class TestAuthentication(BaseAuthentication): def authenticate(self, request): """ 用户认证,如果验证成功后返回元组: (用户,用户Token) :param request: :return: None,表示跳过该验证; 如果跳过了所有认证,默认用户和Token和使用配置文件进行设置 self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self.user = api_settings.UNAUTHENTICATED_USER() # 默认值为:匿名用户 else: self.user = None if api_settings.UNAUTHENTICATED_TOKEN: self.auth = api_settings.UNAUTHENTICATED_TOKEN()# 默认值为:None else: self.auth = None (user,token)表示验证通过并设置用户名和Token; AuthenticationFailed异常 """ val = request.query_params.get('token') if val not in token_list: raise exceptions.AuthenticationFailed("用户认证失败") return ('登录用户', '用户token') 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. """ passclass TestPermission(BasePermission): message = "权限验证失败" def has_permission(self, request, view): """ 判断是否有权限访问当前请求 Return `True` if permission is granted, `False` otherwise. :param request: :param view: :return: True有权限;False无权限 """ if request.user == "管理员": return True # GenericAPIView中get_object时调用 def has_object_permission(self, request, view, obj): """ 视图继承GenericAPIView,并在其中使用get_object时获取对象时,触发单独对象权限验证 Return `True` if permission is granted, `False` otherwise. :param request: :param view: :param obj: :return: True有权限;False无权限 """ if request.user == "管理员": return Trueclass TestView(APIView): # 认证的动作是由request.user触发 authentication_classes = [TestAuthentication, ] # 权限 # 循环执行所有的权限 permission_classes = [TestPermission, ] def get(self, request, *args, **kwargs): # self.dispatch print(request.user) print(request.auth) return Response('GET请求,响应内容') def post(self, request, *args, **kwargs): return Response('POST请求,响应内容') def put(self, request, *args, **kwargs): return Response('PUT请求,响应内容') |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class MyAuthtication(BasicAuthentication): def authenticate(self, request): token = request.query_params.get('token') #注意是没有GET的,用query_params表示 if token == 'zxxzzxzc': return ('uuuuuu','afsdsgdf') #返回user,auth # raise AuthenticationFailed('认证错误') #只要抛出认证错误这样的异常就会去执行下面的函数 raise APIException('认证错误') def authenticate_header(self, request): #认证不成功的时候执行 return 'Basic reala="api"'class UserView(APIView): authentication_classes = [MyAuthtication,] def get(self,request,*args,**kwargs): print(request.user) print(request.auth) return Response('用户列表') |

二、权限
1、需求:Host是匿名用户和用户都能访问 #匿名用户的request.user = none;User只有注册用户能访问
|
1
2
3
4
5
6
7
8
9
|
from app03 import viewsfrom django.conf.urls import urlurlpatterns = [ # django rest framework url('^auth/', views.AuthView.as_view()), url(r'^hosts/', views.HostView.as_view()), url(r'^users/', views.UsersView.as_view()), url(r'^salary/', views.SalaryView.as_view()),] |
|
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
from django.shortcuts import renderfrom rest_framework.views import APIView #继承的viewfrom rest_framework.response import Response #友好的返回from rest_framework.authentication import BaseAuthentication #认证的类from rest_framework.authentication import BasicAuthenticationfrom app01 import modelsfrom rest_framework import exceptionsfrom rest_framework.permissions import AllowAny #权限在这个类里面from rest_framework.throttling import BaseThrottle,SimpleRateThrottle# Create your views here.# +++++++++++++++认证类和权限类========================class MyAuthentication(BaseAuthentication): def authenticate(self, request): token = request.query_params.get('token') obj = models.UserInfo.objects.filter(token=token).first() if obj : #如果认证成功,返回用户名和auth return (obj.username,obj) return None #如果没有认证成功就不处理,进行下一步 def authenticate_header(self, request): passclass MyPermission(object): message = '无权访问' def has_permission(self,request,view): #has_permission里面的self是view视图对象 if request.user: return True #如果不是匿名用户就说明有权限 return False #否则无权限class AdminPermission(object): message = '无权访问' def has_permission(self, request, view): # has_permission里面的self是view视图对象 if request.user=='haiyun': return True # 返回True表示有权限 return False #返回False表示无权限# +++++++++++++++++++++++++++class AuthView(APIView): authentication_classes = [] #认证页面不需要认证 def get(self,request): self.dispatch return '认证列表'class HostView(APIView): '''需求: Host是匿名用户和用户都能访问 #匿名用户的request.user = none User只有注册用户能访问 ''' authentication_classes = [MyAuthentication,] permission_classes = [] #都能访问就没必要设置权限了 def get(self,request): print(request.user) print(request.auth) return Response('主机列表')class UsersView(APIView): '''用户能访问,request.user里面有值''' authentication_classes = [MyAuthentication,] permission_classes = [MyPermission,] def get(self,request): print(request.user,'111111111') return Response('用户列表') def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ if request.authenticators and not request.successful_authenticator: '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了''' raise exceptions.NotAuthenticated(detail='无权访问') raise exceptions.PermissionDenied(detail=message) |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class SalaryView(APIView): '''用户能访问''' message ='无权访问' authentication_classes = [MyAuthentication,] #验证是不是用户 permission_classes = [MyPermission,AdminPermission,] #再看用户有没有权限,如果有权限在判断有没有管理员的权限 def get(self,request): return Response('薪资列表') def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ if request.authenticators and not request.successful_authenticator: '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了''' raise exceptions.NotAuthenticated(detail='无权访问') raise exceptions.PermissionDenied(detail=message) |
如果遇上这样的,还可以自定制,参考源码

def check_permissions(self, request):
"""
Check if the request should be permitted.
Raises an appropriate exception if the request is not permitted.
"""
for permission in self.get_permissions():
#循环每一个permission对象,调用has_permission
#如果False,则抛出异常
#True 说明有权访问
if not permission.has_permission(request, self):
self.permission_denied(
request, message=getattr(permission, 'message', None)
)
def permission_denied(self, request, message=None):
"""
If request is not permitted, determine what kind of exception to raise.
"""
if request.authenticators and not request.successful_authenticator:
'''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了'''
raise exceptions.NotAuthenticated()
raise exceptions.PermissionDenied(detail=message)
那么我们可以重写permission_denied这个方法,如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class UsersView(APIView): '''用户能访问,request.user里面有值''' authentication_classes = [MyAuthentication,] permission_classes = [MyPermission,] def get(self,request): return Response('用户列表') def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ if request.authenticators and not request.successful_authenticator: '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了''' raise exceptions.NotAuthenticated(detail='无权访问') raise exceptions.PermissionDenied(detail=message) |

2. 全局使用
上述操作中均是对单独视图进行特殊配置,如果想要对全局进行配置,则需要再配置文件中写入即可。
|
1
2
3
4
5
6
7
8
9
10
|
REST_FRAMEWORK = { 'UNAUTHENTICATED_USER': None, 'UNAUTHENTICATED_TOKEN': None, #将匿名用户设置为None "DEFAULT_AUTHENTICATION_CLASSES": [ "app01.utils.MyAuthentication", ], 'DEFAULT_PERMISSION_CLASSES':[ "app03.utils.MyPermission",#设置路径, ]} |
|
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 AuthView(APIView): authentication_classes = [] #认证页面不需要认证 def get(self,request): self.dispatch return '认证列表'class HostView(APIView): '''需求: Host是匿名用户和用户都能访问 #匿名用户的request.user = none User只有注册用户能访问 ''' authentication_classes = [MyAuthentication,] permission_classes = [] #都能访问就没必要设置权限了 def get(self,request): print(request.user) print(request.auth) return Response('主机列表')class UsersView(APIView): '''用户能访问,request.user里面有值''' authentication_classes = [MyAuthentication,] permission_classes = [MyPermission,] def get(self,request): print(request.user,'111111111') return Response('用户列表') def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ if request.authenticators and not request.successful_authenticator: '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了''' raise exceptions.NotAuthenticated(detail='无权访问') raise exceptions.PermissionDenied(detail=message)class SalaryView(APIView): '''用户能访问''' message ='无权访问' authentication_classes = [MyAuthentication,] #验证是不是用户 permission_classes = [MyPermission,AdminPermission,] #再看用户有没有权限,如果有权限在判断有没有管理员的权限 def get(self,request): return Response('薪资列表') def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ if request.authenticators and not request.successful_authenticator: '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了''' raise exceptions.NotAuthenticated(detail='无权访问') raise exceptions.PermissionDenied(detail=message) |
三、限流
1、为什么要限流呢?
答:防爬
2、限制访问频率源码分析
|
1
|
self.check_throttles(request) |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
def check_throttles(self, request): """ Check if request should be throttled. Raises an appropriate exception if the request is throttled. """ for throttle in self.get_throttles(): #循环每一个throttle对象,执行allow_request方法 # allow_request: #返回False,说明限制访问频率 #返回True,说明不限制,通行 if not throttle.allow_request(request, self): self.throttled(request, throttle.wait()) #throttle.wait()表示还要等多少秒就能访问了 |
|
1
2
3
4
5
6
|
def get_throttles(self): """ Instantiates and returns the list of throttles that this view uses. """ #返回对象 return [throttle() for throttle in self.throttle_classes] |
|
1
|
throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES |
|
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
|
class BaseThrottle(object): """ Rate throttling of requests. """ def allow_request(self, request, view): """ Return `True` if the request should be allowed, `False` otherwise. """ raise NotImplementedError('.allow_request() must be overridden') def get_ident(self, request): """ Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR if present and number of proxies is > 0. If not use all of HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR. """ xff = request.META.get('HTTP_X_FORWARDED_FOR') remote_addr = request.META.get('REMOTE_ADDR') num_proxies = api_settings.NUM_PROXIES if num_proxies is not None: if num_proxies == 0 or xff is None: return remote_addr addrs = xff.split(',') client_addr = addrs[-min(num_proxies, len(addrs))] return client_addr.strip() return ''.join(xff.split()) if xff else remote_addr def wait(self): """ Optionally, return a recommended number of seconds to wait before the next request. """ return None |
|
1
2
3
4
5
|
def throttled(self, request, wait): """ If request is throttled, determine what kind of exception to raise. """ raise exceptions.Throttled(wait) |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class Throttled(APIException): status_code = status.HTTP_429_TOO_MANY_REQUESTS default_detail = _('Request was throttled.') extra_detail_singular = 'Expected available in {wait} second.' extra_detail_plural = 'Expected available in {wait} seconds.' default_code = 'throttled' def __init__(self, wait=None, detail=None, code=None): if detail is None: detail = force_text(self.default_detail) if wait is not None: wait = math.ceil(wait) detail = ' '.join(( detail, force_text(ungettext(self.extra_detail_singular.format(wait=wait), self.extra_detail_plural.format(wait=wait), wait)))) self.wait = wait super(Throttled, self).__init__(detail, code) |
下面来看看最简单的从源码中分析的示例,这只是举例说明了一下
|
1
2
3
4
5
6
|
from django.conf.urls import urlfrom app04 import viewsurlpatterns = [ url('limit/',views.LimitView.as_view()),] |
|
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
|
from django.shortcuts import renderfrom rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework import exceptions# from rest_framewor import# Create your views here.class MyThrottle(object): def allow_request(self,request,view): #返回False,限制 #返回True,不限制 pass def wait(self): return 1000class LimitView(APIView): authentication_classes = [] #不让认证用户 permission_classes = [] #不让验证权限 throttle_classes = [MyThrottle, ] def get(self,request): # self.dispatch return Response('控制访问频率示例') def throttled(self, request, wait): '''可定制方法设置中文错误''' # raise exceptions.Throttled(wait) class MyThrottle(exceptions.Throttled): default_detail = '请求被限制' extra_detail_singular = 'Expected available in {wait} second.' extra_detail_plural = 'Expected available in {wait} seconds.' default_code = '还需要再等{wait}秒' raise MyThrottle(wait) |
3、需求:对匿名用户进行限制,每个用户一分钟允许访问10次(只针对用户来说)
a、基于用户IP限制访问频率
流程分析:
- 先获取用户信息,如果是匿名用户,获取IP。如果不是匿名用户就可以获取用户名。
- 获取匿名用户IP,在request里面获取,比如IP= 1.1.1.1。
- 吧获取到的IP添加到到recode字典里面,需要在添加之前先限制一下。
- 如果时间间隔大于60秒,说明时间久远了,就把那个时间给剔除 了pop。在timelist列表里面现在留的是有效的访问时间段。
- 然后判断他的访问次数超过了10次没有,如果超过了时间就return False。
- 美中不足的是时间是固定的,我们改变他为动态的:列表里面最开始进来的时间和当前的时间进行比较,看需要等多久。
具体实现:

b、用resetframework内部的限制访问频率(利于Django缓存)
源码分析:
from rest_framework.throttling import BaseThrottle,SimpleRateThrottle #限制访问频率
请求一进来会先执行SimpleRateThrottle这个类的构造方法
代码实现:
记得在settings里面配置
4、对匿名用户进行限制,每个用户1分钟允许访问5次,对于登录的普通用户1分钟访问10次,VIP用户一分钟访问20次
- 比如首页可以匿名访问
- #先认证,只有认证了才知道是不是匿名的,
- #权限登录成功之后才能访问, ,index页面就不需要权限了
- If request.user #判断登录了没有
四、总结
1、认证:就是检查用户是否存在;如果存在返回(request.user,request.auth);不存在request.user/request.auth=None
2、权限:进行职责的划分
3、限制访问频率
认证
- 类:authenticate/authenticate_header ##验证不成功的时候执行的
- 返回值:
- return None,
- return (user,auth),
- raise 异常
- 配置:
- 视图:
class IndexView(APIView):
authentication_classes = [MyAuthentication,]
- 全局:
REST_FRAMEWORK = {
'UNAUTHENTICATED_USER': None,
'UNAUTHENTICATED_TOKEN': None,
"DEFAULT_AUTHENTICATION_CLASSES": [
# "app02.utils.MyAuthentication",
],
}
权限
- 类:has_permission/has_object_permission
- 返回值:
- True、#有权限
- False、#无权限
- exceptions.PermissionDenied(detail="错误信息") #异常自己随意,想抛就抛,错误信息自己指定
- 配置:
- 视图:
class IndexView(APIView):
permission_classes = [MyPermission,]
- 全局:
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": [
# "app02.utils.MyAuthentication",
],
}
限流
- 类:allow_request/wait PS: scope = "wdp_user"
- 返回值:
return True、#不限制
return False #限制
- 配置:
- 视图:
class IndexView(APIView):
throttle_classes=[AnonThrottle,UserThrottle,]
def get(self,request,*args,**kwargs):
self.dispatch
return Response('访问首页')
- 全局
REST_FRAMEWORK = {
"DEFAULT_THROTTLE_CLASSES":[
],
'DEFAULT_THROTTLE_RATES':{
'wdp_anon':'5/minute',
'wdp_user':'10/minute',
}
}
posted on 2018-05-16 13:02 myworldworld 阅读(283) 评论(0) 收藏 举报

浙公网安备 33010602011771号