烧瓶-无法获取Cookie

时间:2020-04-06 23:16:27

标签: python flask cookies jwt

我有以下端点开始授权流程:

@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)

然后,我从Spotify重定向回到/callback,在响应中设置jwt Cookie,如下所示:

 @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

cookie会显示在我的浏览器控制台的“应用程序”下。


现在,我想从另一个端点获取它们,就像这样:

@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')

但是我将这些Cookie打印为NoneNoneNone

另外,我没有Flask配置...

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

...这可能会阻止Cookie通过http发送。


我想念什么?


OBS:我正在使用Postman测试此端点,并且在标题中,将密钥Access-Control-Allow-Credentials设置为值true

2 个答案:

答案 0 :(得分:3)

根据以上所述,我假设您正在使用基于任何其他框架的前端应用程序,并使用axios,fetch,request等库来访问烧瓶上的API。

因此,您可能会错过了需要在请求中设置标志以允许发送Cookie的想法。请参考以下链接以找到实现方法:

  1. 获取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);

如果不能解决问题,请纠正我。

答案 1 :(得分:0)

以下工作有效(如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); });
  };

我不知道我的邮递员请求中缺少什么,但是现在可以使用了。