禁止(CSRF令牌缺失或不正确。):/api/token/refresh/
在视图中使用@csrf_protect装饰器时,我遇到了错误“禁止(CSRF令牌缺失或不正确):/api/token/token/refresh/'
views.pys.pys.py
@api_view(['POST'])
@renderer_classes([CustomizeJSONRenderer])
@csrf_protect
def refresh_token_view(request):
refresh_token = request.COOKIES.get('refreshtoken')
# check valid refresh token
if refresh_token is None:
raise exceptions.AuthenticationFailed('Authentication credentials were not
provided, please login.')
try:
payload = jwt.decode(refresh_token, settings.REFRESH_TOKEN_SECRET,
algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise exceptions.AuthenticationFailed('expired refresh token, please login
again.')
user = User.objects.filter(id=payload.get('user_id')).first()
# check valid user
if user is None:
raise exceptions.AuthenticationFailed('user not found.')
if not user.is_active:
raise exceptions.AuthenticationFailed('user is inactive.')
access_token = generate_access_token(user) # create new access token
return Response({'access_token': access_token})
When using the @csrf_protect decorator in the view, I encountered the error "Forbidden (CSRF token missing or incorrect): /api/token/refresh/"
views.py
@api_view(['POST'])
@renderer_classes([CustomizeJSONRenderer])
@csrf_protect
def refresh_token_view(request):
refresh_token = request.COOKIES.get('refreshtoken')
# check valid refresh token
if refresh_token is None:
raise exceptions.AuthenticationFailed('Authentication credentials were not
provided, please login.')
try:
payload = jwt.decode(refresh_token, settings.REFRESH_TOKEN_SECRET,
algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise exceptions.AuthenticationFailed('expired refresh token, please login
again.')
user = User.objects.filter(id=payload.get('user_id')).first()
# check valid user
if user is None:
raise exceptions.AuthenticationFailed('user not found.')
if not user.is_active:
raise exceptions.AuthenticationFailed('user is inactive.')
access_token = generate_access_token(user) # create new access token
return Response({'access_token': access_token})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在要使用django命令的HTML模板中写入{%csrf_token%}。
just write {% csrf_token %} in your HTML template where you wants to use your django command.