首页 > 解决方案 > Vue js Django Rest 框架与 JWT 用户身份验证(获取匿名用户) simplejwt simplejwt

问题描述

我得到了令牌。但是无法获取该用户的数据。获取数据的 URL。象征性的工作。//simplejwt simplejwt

class CustomerRetrieveView(generics.RetrieveAPIView):

    queryset = Customer.objects.all()
    permission_classes=(IsAuthenticated,)
    def get(self,request):
                                   ???here correct?????
        queryset=Customer.objects.get(id=request.user)
        serializer=CustomerSerializer(queryset)
        
        return Response(serializer.data)

网址

                ??here correct?????
path('customers/????<int:id>???', views.CustomerRetrieveView.as_view()),

前端

created() { 
      getAPI.get('???????????/customers????????', { headers: { Authorization: `Bearer ${this.$store.state.accessToken}` } })
      .then(response => {
        this.$store.state.APIData = response.data
      })
      .catch(err => {
        console.log(err)
        console.log(`Bearer ${this.$store.state.accessToken}`)
      })

      
        
     
        
        
        
    },

楷模

class Customer(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=11)
    likecus=models.ManyToManyField(smartphone ,verbose_name="b")

    def __str__(self):
        return "User: {}, phone: {}".format(self.user, self.phone)

串行器

class CustomerSerializer(serializers.ModelSerializer):
   

    class Meta:
        model = Customer
        fields = '__all__'

我得到了令牌。但是无法获取该用户的数据。获取数据的 URL。令牌工作我得到了令牌。但是无法获取此用户的数据。获取数据的 URL。令牌工作我得到了令牌。但是无法获取此用户的数据。获取数据的 URL。象征性工作

标签: vue.jsdjango-rest-framework

解决方案


你可以这样做

点安装 djangorestframework-jwt

设置.py

from django.conf import settings
import datetime

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',
    ),
}

JWT_AUTH = {
    'JWT_ENCODE_HANDLER':
    'rest_framework_jwt.utils.jwt_encode_handler',

    'JWT_DECODE_HANDLER':
    'rest_framework_jwt.utils.jwt_decode_handler',

    'JWT_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_payload_handler',

    'JWT_PAYLOAD_GET_USER_ID_HANDLER':
    'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    'JWT_RESPONSE_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_response_payload_handler',

    'JWT_SECRET_KEY': settings.SECRET_KEY,
    'JWT_GET_USER_SECRET_KEY': None,
    'JWT_PUBLIC_KEY': None,
    'JWT_PRIVATE_KEY': None,
    'JWT_ALGORITHM': 'HS256',
    'JWT_VERIFY': True,
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
    'JWT_AUDIENCE': None,
    'JWT_ISSUER': None,

    'JWT_ALLOW_REFRESH': False,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),

    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_AUTH_COOKIE': None,

}

网址.py

from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token

urlpatterns = [
    path(r'^api-token-refresh/', refresh_jwt_token),
    path(r'^api-token-auth/', obtain_jwt_token),
    path(r'^api-token-verify/', verify_jwt_token),
]

curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/


推荐阅读