如何使用 angu 进行HTTP Basic Auth

2024-04-18 08:59:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用django rest framework后端构建ionic应用程序,我无法执行简单的http基本身份验证。在

后端view

class GetActive(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        settings = Setting.objects.filter(active=True)
        for setting in reversed(settings):
            headers = {'Access-Control-Allow-Origin': '*'}
            return Response({
                'youtube_link': setting.youtube_link,
                'text': setting.text}, headers=headers)
        return HttpResponse('not found')

前端api.ts

^{pr2}$

我得到了这个错误:

403 forbidden No 'Access-Control-Allow-Origin' header is present on the requested resource.

但是,如果我删除后端的IsAuthenticated权限并从前端请求中删除头,那么它就可以工作了。在

为了确信当IsAuthenticated处于启用状态时它确实可以工作,我编写了以下python脚本:

import requests
from requests.auth import HTTPBasicAuth

theurl = 'http://localhost:8000/get_active'
username = 'foo'
password = 'bar'

r = requests.get(theurl, auth=HTTPBasicAuth(username, password))
print (r.text)

它工作得很好,所以我只需要js模拟。在


Tags: texthttpgetreturnsettingsaccessyoutubeorigin