【问题标题】:django angular anonymous userdjango 角度匿名用户
【发布时间】:2016-03-29 19:51:42
【问题描述】:

我正在从我的 Angular 客户端向我的 Django 后端发送一个 $http 获取请求,其中 (request.user) 给了我匿名。因此,我可以在服务器端做任何事情。

我在 django 端使用 django-rest-auth 并在客户端使用 angular-django-registration-auth 进行身份验证。身份验证本身是成功的 - 我可以登录并检索从服务器发送的客户端的用户名、电子邮件 ID。

我的请求如下所示:

 var url = "http://localhost:8000/api/exercises/get_exercise/" + exerciseType + "/";

   $http({
            url: url,
            method: 'GET',
            headers: {'X-CSRFToken': $cookies['csrftoken']}
        })

          .success(function(response){

            console.log(response);

           });
      }) 

在我的应用配置中,我添加了以下行:

$httpProvider.defaults.withCredentials = this.use_session;

从我的 chrome 浏览器控制台看到的请求标头如下:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,en-GB;q=0.2
Authorization:Token eb979cb6f179dd2d9056023685e2d02e4e65a58e
Connection:keep-alive
Host:localhost:8000
Origin:http://localhost:8100
Referer:http://localhost:8100/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36

如果我直接在 django 服务器运行的“http://127.0.0.1:8000/api/exercises/get_exercise/2/”上从我的 django api 端点点击相同的 url,则它是成功的,并且请求标头如下:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,en-GB;q=0.2
Cache-Control:max-age=0
Connection:keep-alive
Cookie:csrftoken=GDco30gJ9vki6LDtqJSuQh9hGB0aXp84;     sessionid=94xfwx9zvr4pgd1wx9r0nemjwmy3mowi
Host:127.0.0.1:8000
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36

我看到的不同之处在于,成功的请求发送了 cookie 和会话信息,而我的 Angular 应用程序发送的请求中缺少这些信息。

原因和解决方法是什么?

我的 Django settings.py 有以下内容:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),

}

我的 django 视图如下所示:

from django.contrib.auth.models import User
from rest_framework.authentication import TokenAuthentication,     SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.decorators import authentication_classes
from rest_framework.decorators import permission_classes 

class JSONResponse(HttpResponse):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
    content = JSONRenderer().render(data)
    kwargs['content_type'] = 'application/json'
    super(JSONResponse, self).__init__(content, **kwargs)

#view to get a specific exercise for a particular user
def get_single_exercise_for_user_id(request, exerciseId):

  results = Exercise_state_ui_model.fetch_exercises(request.user.id, exerciseId)

  serializer = ExerciseStateSerializer(results, many=True)
  return JSONResponse(serializer.data)

【问题讨论】:

    标签: angularjs django angular-http django-angular


    【解决方案1】:
    Authorization:Token eb979cb6f179dd2d9056023685e2d02e4e65a58e
    

    让我觉得您需要在该视图上启用令牌身份验证。

    #view to get a specific exercise for a particular user
    @api_view(('GET',))
    def get_single_exercise_for_user_id(request, exerciseId):
    
         results = Exercise_state_ui_model.fetch_exercises(request.user.id, exerciseId)
    
         serializer = ExerciseStateSerializer(results, many=True)
         return Response(serializer.data)
    

    【讨论】:

    • 我已经用我的 settings.py 和 views.py 中的 sn-ps 更新了我的问题。有没有漏掉的可以看看吗?
    • 你需要装饰那个视图。也取出那个JSONresponse,让rest_framework根据客户端的要求决定返回的内容。
    • 太棒了!您的解决方案有效!我浪费了两天时间寻找所有可能的原因!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2011-09-25
    • 2019-06-26
    • 2017-07-07
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    相关资源
    最近更新 更多