使用JWT完成用户认证
url(r’^login/$’, obtain_jwt_token, name=‘login’),
- 注册模块
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
]
- 配置JWT
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'scripts.exceptions.exception_handler',
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
'DEFAULT_PAGINATION_CLASS': 'scripts.pagination.StandardResultsSetPagination',
}
JWT_AUTH = {
'JWT_AUTH_HEADER_PREFIX': 'JWT_',
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_RESPONSE_PAYLOAD_HANDLER': 'apps.users.utils.jwt_response_payload_handler', # return
}
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = [
'apps.users.utils.UsernameMobileAuthBackend', # jwt_user
'django.contrib.auth.backends.ModelBackend' # admin
]
- 重写return
- 在使用JWT做用户验证的时候,我们最好能定制返回值
- 在settings文件中配置JWT的返回信息
- 同时重写
jwt_response_payload_handler()
,指定返回值
import re
import datetime
from .models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.auth.backends import ModelBackend
def get_user_by_account(account):
user = User.objects.get(username=account)
return user
class UsernameMobileAuthBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
user = get_user_by_account(username)
if user is not None and user.check_password(password):
return user
def jwt_response_payload_handler(token, user=None, request=None):
"""retuen token_info"""
user.is_staff = True
user.last_login = str(datetime.datetime.today())
user.save()
return {
'id': user.id,
'token': token,
'username': user.username,
"job_number": user.job_number,
}
使用ViewSet
router = SimpleRouter()
router.register(r’’, UserViewSet)
urlpatterns += router.urls
view.py
- 我们继承自viewsets.ModelViewSet之后,我们就拥有了父类所有的方法
- 当父类方法无法满足我们的需求时,需要重写父类方法
- viewset不同于APIView,不同的请求对应的方法的名称是不同的
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('id')
serializer_class = UserSerializer
permission_classes = [IsAuthenticated]
def create(self, request, *args, **kwargs):
serializers = self.get_serializer(data=request.data)
serializers.is_valid(raise_exception=True)
serializers.validated_data["is_active"] = True # value
self.perform_create(serializers)
headers = self.get_success_headers(serializers.data)
return Response(serializers.data, status=status.HTTP_201_CREATED, headers=headers)
使用logout()
url(’^logout/$’, LogoutView.as_view(), name=“logout”),
class LogoutView(View):
def get(self, request):
logout(request)
return render(request, 'login.html')
评论区