Django Rest Framework - response.set_cookie() 不在浏览器中设置 cookie,但在邮递员和可浏览 api 中工作
Posted
技术标签:
【中文标题】Django Rest Framework - response.set_cookie() 不在浏览器中设置 cookie,但在邮递员和可浏览 api 中工作【英文标题】:Django Rest Framework - response.set_cookie() not setting cookie in browser but working in postman and in browsable api 【发布时间】:2021-11-02 21:24:18 【问题描述】:我正在努力在 httponly cookie 中设置 jwt 令牌。我尝试了很多解决方案但没有工作。我正在使用本地主机“127.0.0.1”但是当我尝试登录服务器发送的 cookie 时不会显示在我的前端工作在“127.0.0.1:5501”但是如果我尝试使用可浏览的 api 在“127.0.0.1:8000”工作" 它运行良好,我可以轻松检查我的 cookie。
我也注意到了一件奇怪的事情。如果我通过前端“127.0.0.1:5501”登录,cookie 未设置,但如果我尝试使用在“127.0.0.1:8000”工作的可浏览 api,然后切换到“127.0.0.1:5501”选项卡,我可以看到饼干他们也是。这是一件非常奇怪的事情,我不知道这背后的原因。
请帮我解决这个问题。
Views.py
class LoginView(APIView):
def post(self,request,format=None):
data = request.data
response = Response()
username = data.get('username', None)
password = data.get('password', None)
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
data = get_tokens_for_user(user)
response.set_cookie(
key = settings.SIMPLE_JWT['AUTH_COOKIE'],
value = data["access"],
expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'],
secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'],
httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'],
samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE']
)
csrf.get_token(request)
response.data = "Success" : "Login successfully","data":data
return response
else:
return Response("No active" : "This account is not active!!",status=status.HTTP_404_NOT_FOUND)
else:
return Response("Invalid" : "Invalid username or password!!",status=status.HTTP_404_NOT_FOUND)
获取 API 请求
async function login(email,password)
let response = await fetch('http://127.0.0.1:8000/api/account/login/',
method: 'POST',
headers:
"Accept": "application/json",
"Content-Type": "application/json",
,
withCredentials: true,
body: JSON.stringify(
'username': email,
'password': password
)
)
return response;
Settings.py 文件
ALLOWED_HOSTS = ['127.0.0.1']
CORS_ALLOW_HEADERS = default_headers + (
'Access-Control-Allow-Origin',
)
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://127.0.0.1:5501",
]
# ////////////////custom settings/////////////source : ***/////////////////////
'AUTH_COOKIE': 'access_token', # Cookie name. Enables cookies if value is set.
'AUTH_COOKIE_DOMAIN': None, # A string like "example.com", or None for standard domain cookie.
'AUTH_COOKIE_SECURE': False, # Whether the auth cookies should be secure (https:// only).
'AUTH_COOKIE_HTTP_ONLY' : True, # Http only cookie flag.It's not fetch by javascript.
'AUTH_COOKIE_PATH': '/', # The path of the auth cookie.
'AUTH_COOKIE_SAMESITE': 'Lax', # Whether to set the flag restricting cookie leaks on cross-site requests.
# This can be 'Lax', 'Strict', or None to disable the flag.
邮递员演示
可浏览的 api 演示
前端演示
【问题讨论】:
【参考方案1】:如果您也在为这个问题苦苦挣扎。只需确保您具有上述设置并遵循此简单更新即可。
let response = await fetch('http://127.0.0.1:8000/api/account/login/',
method: 'POST',
headers:
"Accept": "application/json",
"Content-Type": "application/json",
,
credentials: 'include',
body: JSON.stringify(
'username': email,
'password': password
)
)
它应该只是凭证。
【讨论】:
以上是关于Django Rest Framework - response.set_cookie() 不在浏览器中设置 cookie,但在邮递员和可浏览 api 中工作的主要内容,如果未能解决你的问题,请参考以下文章
Django中rest_framework的APIView,序列化组件和视图组件
在 django-rest-framework 中插入 django-allauth 作为端点
Django中rest_framework的认证组件,权限组件,频率组件,序列化组件的最简化版接口
Django Rest Framework 反向和 SimpleRouter
Django Rest Framework组件:解析器JSONParserFormParserMultiPartParserFileUploadParser