【发布时间】:2018-12-23 03:44:40
【问题描述】:
我使用 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,
)
我的urls.py 包含底部静态文件的全部内容:
urlpatterns = [
# ..all api paths
url(r'^', serve_html, name='serve_html'),
]
我使用TokenAuthentication 和SessionAuthentication:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
并且需要用户登录的api请求有如下装饰器:
@authentication_classes((SessionAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
附录:我注意到在跨域运行它时,没有 sessionid cookie(并且一切正常),但是当我尝试在同源上托管反应文件时,有sessionid cookie(并返回 403 Forbidden)。
很抱歉这个开放式问题,但我已经无能为力了;我真的不知道为什么它不起作用。
【问题讨论】:
-
对于带有
IsAuthenticated的端点,您需要传递令牌。 -
运行
curl -X GET http://xxx/yoururl/ -H 'Authorization: Token 69b...07'时终端的结果是什么 -
我将令牌传递给所有需要它的端点,如下所示:
await fetch(${API_HOST}/logout,{ method: 'POST', headers: {'Authorization':Token ${Cookies.get('auth_token')}}});
标签: python django django-rest-framework create-react-app