drf结合Jwt和IsAuthenticated对用户进行登录验证

用户信息(userinfo.html)需要在登录的基础上查看。所以结合jwt和IsAuthenticated对用户进行权限的验证。

首先,要在settings.py文件中进行如下配置:


REST_FRAMEWORK = {

    # 权限认证
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    # 身份验证
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

在视图函数中导入IsAuthenticated并使用:
 

from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import RetrieveAPIView
from .serializers import UserInfoSerialize


'''使用RetrieveAPIView并重写get_object可直接返回网页中登录的用户对象'''
class UserInfoView(RetrieveAPIView):

    serializer_class = UserInfoSerialize
    
    permission_classes = (IsAuthenticated,)

    def get_object(self):
        print('************************userinfo******************************')
        print(self.request.user)
        return self.request.user

其中serializers.py文件:

from rest_framework import serializers
from .models import User


'''用户中心信息的显示'''
class UserInfoSerialize(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('username', 'phone', 'email', 'first_name', 'fixtel', 'qq', 'birth')

model.py文件:

class User(AbstractUser):
    phone = models.CharField(max_length=11, unique=True, verbose_name='手机号码')
    fixtel = models.CharField(max_length=11, unique=True, verbose_name='固定电话', null=True)
    qq = models.CharField(max_length=11, unique=True, verbose_name='qq', null=True)
    birth = models.DateField(verbose_name='出生日期', null=True)
    faceimg = models.ImageField(verbose_name='头像')

    class Meta:
        db_table = 'users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

配置login的url时,使用obtain_jwt_token,可生成jwt-token:

from django.conf.urls import url, include
from . import views
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
    url(r'^userinfo/', views.UserInfoView.as_view()),
    url(r'^login/', obtain_jwt_token),


]

在login.js文件中将token存入localStorage.token:

    $.ajax(
        {
            url: 'http://127.0.0.1:8000/user/login/',
            type: 'POST',
            data: trans_str,
            contentType: 'application/json',
            dataType:'json',
            success: function (data) {
 
                localStorage.clear()
                localStorage.token = data.token
                localStorage.username = data.username
                location.href = '/index.html'
            },
            error: function () {
                alert('用户名或密码错误!')
            }
        })

在userinfo.js文件中对userinfo.html做ajax的get请求,进行权限校验:
 

function ShowUser() {
    $.ajax({
        url:'http://127.0.0.1:8000/user/userinfo/',
        type:'GET',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Authorization", "JWT " + localStorage.token);
        },
        success: function (data) {
              console.log('ok')
            },
        error: function () {
                alert('failed')
            }
    })


}
$(function () {
    ShowUser();

})

此时,若是用户已登录,便可查看userinfo.html页面,否则报错(401)。

猜你喜欢

转载自blog.csdn.net/a1213284679/article/details/85710422
今日推荐