python - 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'),
]
我使用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
被返回)。
很抱歉这个开放式问题,但我在这里无能为力;我真的不知道为什么它不起作用。
解决方案
您不需要SessionAuthentication
该类,因为您使用的是基于令牌的 HTTP 身份验证方案。这应该可以解决问题:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
希望这可以帮助。
推荐阅读
- machine-learning - 如何处理目标变量中的时间步长与预测问题中的特征之间的不匹配?
- python - Scipy 没有显示正确的特征值?
- python - Pandas:分组并按行标签访问单元格以避免循环
- r - 使用 column_spec 的列宽在 KableExtra 中不起作用
- python - 如何拆分每个子列表中具有固定数量项目的列表
- python - 我的 Python 游戏没有像预期的那样运行
- javascript - 仅当 TextField 和 Select 都有值时如何启用按钮
- c - 对于一个 16 位的整型变量,你能给变量赋值 72368 吗?
- sql - 对子查询的结果做一个案例
- sql - 从数据透视表中与员工表没有关联的属性中排除所有