首页 > 解决方案 > Django 和 React 被 403 禁止

问题描述

我使用 create-react-app 结合 Django Rest Framework 来制作一个小型站点。npm start当我从一个端口到另一个端口使用并点击 Django API 时,一切都运行良好。但是,当我npm build从 Django 应用程序中处理静态反应文件并提供它们时,我会403 forbidden遇到许多端点。我认为这与 CSRF 有关,但我不知道是什么。

我从以下位置提供静态文件views.py

@api_view(['GET'])
def serve_html(request):
    try:
        with open(os.path.join(REACT_APP_DIR, 'build', 'index.html')) as f:
            return HttpResponse(f.read())
    except FileNotFoundError:
        return HttpResponse(
            """
            This URL is only used when you have built the production
            version of the app. Visit http://localhost:3000/ instead, or
            run `yarn run build` to test the production version.
            """,
            status=501,
        )

Myurls.py包含底部静态文件的全部内容:

urlpatterns = [
    # ..all api paths
    url(r'^', serve_html, name='serve_html'),
]

我使用TokenAuthenticationSessionAuthentication

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

而需要用户登录的api请求有如下装饰器:

@authentication_classes((SessionAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))

附录:我注意到当跨域运行它时,没有sessionidcookie(并且一切正常),但是当我尝试在同源上托管反应文件时,有一个sessionidcookie(并且403 Forbidden被返回)。

很抱歉这个开放式问题,但我在这里无能为力;我真的不知道为什么它不起作用。

标签: pythondjangodjango-rest-frameworkcreate-react-app

解决方案


您不需要SessionAuthentication该类,因为您使用的是基于令牌的 HTTP 身份验证方案。这应该可以解决问题:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

希望这可以帮助。


推荐阅读