cph*_*117 2 python django django-rest-framework create-react-app
我使用 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,
)
Run Code Online (Sandbox Code Playgroud)
我的urls.py底部包含静态文件的总览:
urlpatterns = [
# ..all api paths
url(r'^', serve_html, name='serve_html'),
]
Run Code Online (Sandbox Code Playgroud)
我使用TokenAuthentication和SessionAuthentication:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
Run Code Online (Sandbox Code Playgroud)
而需要用户登录的api请求有以下装饰器:
@authentication_classes((SessionAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
Run Code Online (Sandbox Code Playgroud)
附录:我注意到,当跨域运行它时,没有sessionidcookie(并且一切正常),但是当我尝试在同源上托管react文件时,有一个sessionidcookie(并且403 Forbidden返回)。
抱歉问了这个开放式问题,但我已经无计可施了;我真的不知道为什么它不起作用。
小智 6
您不需要该类SessionAuthentication,因为您使用的是基于令牌的 HTTP 身份验证方案。这应该可以解决问题:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
3910 次 |
| 最近记录: |