session方法;
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
class UsersProfileAPIView(APIView):
authentication_classes = [SessionAuthentication, BasicAuthentication] #认证方式
permission_classes = [IsAuthenticated] #是否已经认证
def get(self, request):
users = UsersProfile.objects.all()
users_serializer = UsersSerializer(users, many=True)
return Response(users_serializer.data)
访问127.0.0.1:9000/api/users/
必须登陆才能得到数据
Token方法:
注册应用:
'rest_framework.authtoken',
在views.py中:
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
class UsersProfileAPIView(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
users = UsersProfile.objects.all()
users_serializer = UsersSerializer(users, many=True)
return Response(users_serializer.data)
在根urls.py中:
from rest_framework.authtoken import views as authviews
path('api-token-auth/', authviews.obtain_auth_token),
post请求api-token-auth/得到Token。在访问/api/users/时,将Token信息加入请求数据的请求头中,才能得到数据
请求头格式:Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
base64url转码格式
bash# cnpm install base64url
bash# node
>const base64url = require('base64url')
> base64url("rourou")
'cm91cm91'
> base64url.decode('cm91cm91')
'rourou'
使用jwt实现身份验证
pip3 install djangorestframework-jwt
在settings中 (全局使用JWT进行身份认证)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
)
}
在试图中使用(局部使用)
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
class UsersSeriaView(APIView):
authentication_classes = [JSONWebTokenAuthentication]
permission_classes = [IsAuthenticated]
在urls中:
from rest_framework_jwt.views import obtain_jwt_token
path('jwt-token-auth/', obtain_jwt_token),
在settings中设置过期时间
import datetime
JWT_AUTH = {
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
}
在postman中:
访问api-token-auth/得到字符串,在使用get方式访问资源时使用
Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJ1c2VybmFtZSI6InF3ZSIsImV4cCI6MTU3MTY0ODQwOCwiZW1haWwiOiIxMTExQHJvdXJvdS5jb20ifQ.tZ2fxvhejzrZ3xvZbKo1xG113NursK6WHkRIhwGlFZE
网友评论