如何解决使用 Django Rest Framework TokenAuthentication
我正在准备我的应用程序的身份验证(使用 TokenAuthentication)过程,为了安全起见,我想将令牌存储到 HttpOnly cookie 中。
为此,我创建了自己的视图来获取令牌。
事实上,我正在覆盖默认的 rest_framework.authtoken.views.ObtainAuthToken
,如下所示:
from django.conf import settings
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.response import Response
class ObtainCookieAuthToken(ObtainAuthToken):
"""
Override default ObtainAuthToken view from rest_framework to set the token into a
HttpOnly cookie.
The 'secure' option will depend on the settings.DEBUG value.
"""
def post(self,request,*args,**kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token,created = Token.objects.get_or_create(user=user)
response = Response({
'user': "user is %s" % user.full_name,'other': "some other info here"
})
response.set_cookie(
"auth-token",token,httponly=True,secure=settings.DEBUG,)
return response
在我的网址中:
from django.urls import include,path,re_path
from .base.authentication.obtain_cookie_auth_token import ObtainCookieAuthToken
urlpatterns = [
# ...
path('api/api-token-auth/',ObtainCookieAuthToken.as_view()),# ...
]
之后,在将覆盖默认 rest_framework.authentication.TokenAuthentication
的自定义类中,我将检查该 cookie 以从中检索令牌。
问题是当我的 ObtainCookieAuthToken
被有效调用时没有创建 cookie。
我错过了什么吗?我不明白为什么不创建 cookie...我认为 set_cookie
的 response
可以解决问题。
顺便说一下,这里是我如何调用这个 API 端点,我的 login()
方法来自我的 Vuejs 前端:
login () {
this.axios
.post('api-token-auth/',{
username: this.form.username || this.lastLoggedInUser.username,password: this.form.password
})
.then(response => {
this.$router.push({ name: 'Home' })
})
.catch(error => {
console.log("error : ",error)
})
},
奇怪的是它似乎出现在响应头中:
虽然在其他类似帖子中的问题是“如何”,但这里是“为什么它不起作用?”
预先感谢您的帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。