Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 800
8-Bit Borges Avatar asked Apr 06 '20 23:04

8-Bit Borges


1 Answers

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.

like image 93
Dhruv Agarwal Avatar answered Sep 29 '22 22:09

Dhruv Agarwal