Cookies are not being set on browser Django

I'm making a webapp in Django and Electron using websockets and I wanted to insert one of the socket responses into the user's cookies, but unfortunately I don't know why but they are not being inserted, here is an example of what I am doing:

in the response.cookies printout something like this appears: Cookies defined in the response: Set-Cookie: image_data="pls work"; expires=Tue, 21 May 2024 16:22:33 GMT; Max-Age=3600; Path=/

here is my code if you have any ideas or need any part of the code I will provide it, thank you.


def process_screenshot(request):
    call = identificador_unico(request)
    print("call:", call)
    if request.method == 'POST':
        image_content = request.POST.get('image_content')
        if image_content:
            print("String em base64 recebida com sucesso.")
                # Decodifica a string em base64 para obter os dados binários da imagem
                image_data = base64.b64decode(image_content)
                print("base64", image_data[:20])
                # Salva os dados binários da imagem em um arquivo
                file_path = 'frames/screenshot.jpg'
                with open(file_path, 'wb') as f:
                image_content = "pls work"
                # Salva image_data nos cookies
                response = JsonResponse({'message': 'Imagem processada com sucesso'})
                response.set_cookie('image_data', image_content, max_age=3600,secure=False,samesite=None)  # Expira em 1 hora
                print("Cookies definidos na resposta:", response.cookies)
                return response
            except Exception as e:
                # Se ocorrer algum erro ao decodificar a string em base64 ou salvar o arquivo
                print("Erro ao processar imagem:", e)
                return JsonResponse({'error': 'Erro ao processar imagem'}, status=500)
            # Se nenhuma string em base64 for recebida
            print("Nenhuma string em base64 recebida.")
            return JsonResponse({'error': 'Nenhuma string em base64 recebida'}, status=400)
        # Se a solicitação não for do tipo POST
        return JsonResponse({'error': 'Método não permitido'}, status=405)

printscreen of cookies on browser:

enter image description here

There is a problem with the way you are setting Cookie in process_screenshot(). If the SameSite attribute of a Cookie is set to None, it requires a secure context i.e. the Cookie must have a Secure attribute. You are violating that principle here:

response.set_cookie('image_data', image_content, max_age=3600, samesite=None, secure=False)

Change it to this and it will work:

response.set_cookie('image_data', image_content, max_age=3600, samesite=None, secure=True)
Back to Top