Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
Flask - unable to get cookies

I have the following endpoint starting an Authorization flow:

@spotify_auth_bp.route("/index", methods=['GET', 'POST'])
def spotify_index():
    CODE = "code"
    CLIENT_ID =   os.environ.get('SPOTIPY_CLIENT_ID')
    SCOPE = os.environ.get('SPOTIPY_SCOPE')
    REDIRECT_URI = os.environ.get('SPOTIPY_REDIRECT_URI')

    SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"

    return redirect("{}?response_type={}&client_id={}&scope={}&redirect_uri={}".format(
        SPOTIFY_AUTH_URL, CODE, CLIENT_ID, SCOPE, REDIRECT_URI), code=302)

Then I get redirect back from Spotify to /callback, where I am setting jwt cookies in my response, like so:

 @spotify_auth_bp.route("/callback", methods=['GET', 'POST'])
 def spotify_callback():
    token = user.encode_access_token(access_token)
    a11n_h, a11n_d, a11n_s = token.decode().split('.')
    response = make_response(redirect('http://localhost/about', code=302))
    response.set_cookie('a11n.h', a11n_h)
    response.set_cookie('a11n.d', a11n_d) 
    response.set_cookie('a11n.s', a11n_s, httponly=True)  

    return response

And cookies show up in my browser console, under 'Application'.


Now I would like to get them from another endpoint, like so:

@spotify_auth_bp.route("/get_token/<user_id>", methods=['GET', 'POST'])
def get_token(user_id):
    # get access token cookies
    a11n_h = request.cookies.get('a11n.h')
    a11n_d = request.cookies.get('a11n.d')
    a11n_s = request.cookies.get('a11n.s')

But I'm printing these cookies as None, None, None

also, I have NO Flask config...

app.config.update(
    SESSION_COOKIE_SECURE=True,
    SESSION_COOKIE_SAMESITE='Lax',
)

...which could prevent cookies from being sent over http.


What am I missing?


OBS: I'm testing this endpoint using Postman, and in Headers I've set the key Access-Control-Allow-Credentials to the value true.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

According to the above, i assume you are using a frontend application based on any other framework and using libraries like axios, fetch, request, etc to hit API on the flask.

So, you might have missed out that you need to set a flag in request to allow sending cookies. Refer to below links to find ways to do it:

  1. Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Sending_a_request_with_credentials_included
    fetch('https://example.com', {
      credentials: 'include'
    });
  1. XMLHttpRequest
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://example.com/', true);
    xhr.withCredentials = true;
    xhr.send(null);

Correct me, if doesn't solve the problem.

over 4 years ago · Santiago Trujillo Relatório

0

the following worked (as suggested in the answer from Dhruv Agarwal):

getToken(event) {
    const {userId} = this.props
    const options = {
      url: `${process.env.REACT_APP_WEB_SERVICE_URL}/get_token/1`,
      method: 'get',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${window.localStorage.authToken}`,
      }
    };

    axios.defaults.withCredentials = true // <--------------------

    return axios(options)
    .then((res) => {
      console.log('res.data.data)
    })    
    .catch((error) => { console.log(error); });
  };

I don't know what was missing in my Postman request, but now it's functional.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda