代码之家  ›  专栏  ›  技术社区  ›  TJB

令牌身份验证在Django Rest框架上不起作用

  •  1
  • TJB  · 技术社区  · 7 年前

    {"detail":"Authentication credentials were not provided."}
    

    设置文件

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    
        # My Apps
        'rest_framework',
        'rest_auth',
        'rest_framework.authtoken',
    ]
    
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework.authentication.SessionAuthentication',
            'rest_framework.authentication.TokenAuthentication',
        ],
    }
    

    网址

    from django.urls import path, include
    from rest_framework.routers import DefaultRouter
    from rest_framework.authtoken import views
    
    from api.views.some_model import MyViewSet
    
    urlpatterns = [
        path('', include(router.urls)),
        path('rest-auth/', include('rest_auth.urls')),
        path('api-token-auth/', views.obtain_auth_token)
    ]
    

    视图集

    from rest_framework.viewsets import ModelViewSet
    from rest_framework.authentication import SessionAuthentication, TokenAuthentication
    from rest_framework.permissions import IsAuthenticated
    
    from some_app.models import SomeModel
    from api.serializers.exams import SomeModelSerializer
    
    
    class ExamViewSet(ModelViewSet):
        permission_classes = (IsAuthenticated,)
        authentication_classes = (TokenAuthentication, SessionAuthentication)
    
        queryset = SomeModel.objects.all()
        serializer_class = SomeModelSerializer
    

    获取响应的Python脚本

    import requests
    import json
    
    data = {
        "username": "myemail@gmail.com",
        "password": "password124"
    }
    url = "http://localhost:8002/api/v1/api-token-auth/"
    response = requests.post(url, data=data)
    token = json.loads(response.text).get('token')
    
    if token:
        token = f"Token {token}"
        headers = {"Authentication": token}
        response = requests.get("http://localhost:8002/api/v1/model/", headers=headers)
        print(response.text)
    else:
        print('No Key')
    
    1 回复  |  直到 7 年前
        1
  •  7
  •   neverwalkaloner    7 年前

    标头名称应为 Authorization Authentication :

    headers = {"Authorization": token}
    response = requests.get("http://localhost:8002/api/v1/model/", headers=headers)
    
        2
  •  0
  •   Ryabchenko Alexander    4 年前

     -H  "Authorization: Token 8fa36c01df3bb9ed31fc2329c53a9fe2cac72966"