Django Rest Framework - response.set_cookie() 不在浏览器中设置 cookie 但在 postman 和可浏览中工作 api
Django Rest Framework - response.set_cookie() not setting cookie in browser but working in postman and in browsable api
我正在努力在 httponly cookie 中设置 jwt 令牌。我尝试了很多解决方案但没有用。我正在使用本地主机“127.0.0.1”,但是当我尝试登录时,服务器发送的 cookie 不会显示在我在“127.0.0.1:5501”工作的前端,但如果我尝试使用 Browsable api 在“127.0”工作.0.1:8000" 它工作正常,我可以轻松检查我的 cookie。
我也发现了一件奇怪的事。如果我通过前端“127.0.0.1:5501”登录,未设置 cookie,但如果我尝试使用可浏览的 api 在“127.0.0.1:8000”工作,然后切换到我的“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 : Whosebug/////////////////////
'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演示
前端演示
如果您也在为这个问题苦恼。只需确保您有上述设置并遵循这个简单的更新即可。
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
})
})
它应该只是 凭据。
我正在努力在 httponly cookie 中设置 jwt 令牌。我尝试了很多解决方案但没有用。我正在使用本地主机“127.0.0.1”,但是当我尝试登录时,服务器发送的 cookie 不会显示在我在“127.0.0.1:5501”工作的前端,但如果我尝试使用 Browsable api 在“127.0”工作.0.1:8000" 它工作正常,我可以轻松检查我的 cookie。
我也发现了一件奇怪的事。如果我通过前端“127.0.0.1:5501”登录,未设置 cookie,但如果我尝试使用可浏览的 api 在“127.0.0.1:8000”工作,然后切换到我的“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 : Whosebug/////////////////////
'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演示
前端演示
如果您也在为这个问题苦恼。只需确保您有上述设置并遵循这个简单的更新即可。
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
})
})
它应该只是 凭据。