安装
pip install djangorestframework
认证
简单示例
from rest_framework.views import APIView
from rest_framework import exceptions
class MyAuthentication(object):
def authenticate(self, request):
token = request._request.GET.get('token')
# 获取用户名和密码,然后去数据校验
if not token:
raise exceptions.AuthenticationFailed("用户认证失败")
# 返回一个元组
return ("abc", None)
def authenticate_header(self,val):
pass
class CrawlAll(APIView):
authentication_classes = [MyAuthentication, ]
def get(self, request, *args, **kwargs):
# 获取abc和None
print(request.user, request.auth)
return HttpResponse('GET')
def post(self, request, *args, **kwargs):
return HttpResponse('POST')
def put(self, request, *args, **kwargs):
return HttpResponse('PUT')
示例项目
- 模型
from django.db import models
class UserInfo(models.Model):
user_type_choices = ((1, '普通用户'), (2, 'VIP'), (3, 'SVIP'))
user_type = models.IntegerField(choices=user_type_choices)
username = models.CharField(max_length=32, unique=True)
password = models.CharField(max_length=64)
class UserToken(models.Model):
user = models.OneToOneField(to='UserInfo', on_delete=models.CASCADE)
token = models.CharField(max_length=64)
- 路由
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from api import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/v1/auth/$', views.AuthView.as_view()),
]
- 视图
from django.http import JsonResponse
from rest_framework.views import APIView
from api.models import UserInfo, UserToken
def md5(user):
import hashlib
import time
ctime = str(time.time())
m = hashlib.md5(bytes(user, encoding='utf-8'))
m.update(bytes(ctime, encoding='utf-8'))
return m.hexdigest()
class AuthView(APIView):
'''用户登录成功后生成token,并保存在数据库中'''
def post(self, request, *args, **kwargs):
ret = {'code': 1000, 'msg': None}
try:
user = request._request.POST.get('username')
password = request._request.POST.get('password')
obj = UserInfo.objects.filter(username=user, password=password).first()
# print(obj)
if not obj:
ret['code'] = 1001
ret['msg'] = '用户名或者密码错误'
# 创建token
token = md5(user)
print(token)
UserToken.objects.update_or_create(user=obj, defaults={'token': token})
except Exception as e:
print(e)
return JsonResponse(ret)
认证类的基本使用
# 认证类,返回的情况有三种
# 1、认证失败,返回抛出的异常 `{"detail": "认证失败"}`
# 2、认证为空,返回为匿名用户(request.user, request.auth)为(AnonymousUser ,None)
# 3、认证成功,返回认证的用户信息
class MyAuthtication(object):
def authenticate(self, request):
try:
# 获取token
token = request._request.GET.get('token')
# 去数据库校验token
user_token = UserToken.objects.filter(token=token).first()
print(user_token)
if not token:
raise exceptions.AuthenticationFailed('无权限,请登录!')
return (user_token.user, user_token)
except Exception as e:
print(e)
def authenticate_header(self, val):
pass
class OrderView(APIView):
# 添加认证类,可以添加多个认证类
authentication_classes = [MyAuthtication, ]
def get(self, request, *args, **kwargs):
print(request.user, request.auth)
ret = {'code': 1000, 'mes': None, 'data': None}
ret['data'] = ORDER_DICT
return JsonResponse(ret)
认证的全局使用
- 在settings配置文件中添加
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ['api.utils.auth.MyAuthtication'],
# 当认证为匿名用户时,request.user = '匿名用户'/None
'UNAUTHENTICATED_USER': lambda: '匿名用户', # None
# 当认证为匿名用户时,request.auth = None
'UNAUTHENTICATED_TOKEN': None,
}
- 将认证类写到新的地方
from api.models import UserInfo, UserToken
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication,BasicAuthentication
class MyAuthtication(BaseAuthentication):
def authenticate(self, request):
# 获取token
token = request._request.GET.get('token')
try:
# 去数据库校验token
user_token = UserToken.objects.get(token=token)
except Exception:
raise exceptions.AuthenticationFailed('无权限,请登录!')
return (user_token.user, user_token)
class MyAuthtication1(BasicAuthentication):
def authenticate(self, request):
pass
def authenticate_header(self, val):
pass
- 在全局认证的过程中,如果想去掉认证,可以使用
authentication_classes = []
去掉认证
django-rest-framework中内置的认证
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
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
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(':')
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
class SessionAuthentication(BaseAuthentication):
"""
Use Django's session framework for authentication.
"""
def authenticate(self, request):
"""
Returns a `User` if the request session currently has a logged in user.
Otherwise returns `None`.
"""
# Get the session-based user from the underlying HttpRequest object
user = getattr(request._request, 'user', None)
# Unauthenticated, CSRF validation not required
if not user or not user.is_active:
return None
self.enforce_csrf(request)
# CSRF passed with authenticated user
return (user, None)
def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication.
"""
reason = CSRFCheck().process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
class TokenAuthentication(BaseAuthentication):
"""
Simple token based authentication.
Clients should authenticate by passing the token key in the "Authorization"
HTTP header, prepended with the string "Token ". For example:
Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
"""
keyword = 'Token'
model = None
def get_model(self):
if self.model is not None:
return self.model
from rest_framework.authtoken.models import Token
return Token
"""
A custom token model may be used, but must have the following properties.
* key -- The string identifying the token
* user -- The user to which the token belongs
"""
def authenticate(self, request):
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != self.keyword.lower().encode():
return None
if len(auth) == 1:
msg = _('Invalid token header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid token header. Token string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
try:
token = auth[1].decode()
except UnicodeError:
msg = _('Invalid token header. Token string should not contain invalid characters.')
raise exceptions.AuthenticationFailed(msg)
return self.authenticate_credentials(token)
def authenticate_credentials(self, key):
model = self.get_model()
try:
token = model.objects.select_related('user').get(key=key)
except model.DoesNotExist:
raise exceptions.AuthenticationFailed(_('Invalid token.'))
if not token.user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
return (token.user, token)
def authenticate_header(self, request):
return self.keyword
class RemoteUserAuthentication(BaseAuthentication):
"""
REMOTE_USER authentication.
To use this, set up your web server to perform authentication, which will
set the REMOTE_USER environment variable. You will need to have
'django.contrib.auth.backends.RemoteUserBackend in your
AUTHENTICATION_BACKENDS setting
"""
# Name of request header to grab username from. This will be the key as
# used in the request.META dictionary, i.e. the normalization of headers to
# all uppercase and the addition of "HTTP_" prefix apply.
header = "REMOTE_USER"
def authenticate(self, request):
user = authenticate(remote_user=request.META.get(self.header))
if user and user.is_active:
return (user, None)
- 必用认证类–BaseAuthentication,自定义认证类继承BaseAuthentication
from rest_framework.authentication import BaseAuthentication
- BasicAuthentication
基于浏览器请求头的认证类,首先获取请求的请求头,然后获取浏览器中输入的用户名和密码,再加以认证 - 其他认证类时基于django 内部的认证实现,实际生产和生活中的用处不大