2013-03-28 69 views
2

我正在使用Flask構建一個RESTful應用程序,它將使用會話來跟蹤登錄的用戶。下面是我改編自這個Flask tutorialIn Flask如何使用安全會話以curl驗證用戶?

@mod.route('/login/', methods=['GET', 'POST']) 
def login(): 
    user = User.query.filter_by(email=request.json['email']).first() 
    # we use werkzeug to validate user's password 
    if user and check_password_hash(user.password, request.json['password']): 
    # the session can't be modified as it's signed, 
    # it's a safe place to store the user id 
    session['user_id'] = user.id 
    resp = jsonify({'status':'authenticated'}) 
    else: 
    resp = jsonify({'status':'Invalid usernam/password'}) 
    resp.status_code = 401 
    return resp 

的登錄密碼,當用戶第一次登錄時,我存儲他們的用戶ID在會話中,這樣當同一個用戶請求資源,該數據是定製對他們說:

@mod.route('/address/') 
@requires_login 
def user_data(): 
    user = User.query.filter_by(id=session['usr_id']).first 
    resp = jsonify(user.address) 
    return resp 

如果我在登錄後發出此命令:

curl http://localhost:5000/address/ 

我收到:

{"status": 401, "message": "Unauthorized"} 

而不是我登錄的用戶的地址信息。 任何人都可以告訴我如何在隨後的捲曲調用中使用會話來返回特定於cookie中存儲的用戶標識的數據?

回答

6

到您的登錄請求的響應將包含一個Set-Cookie頭看起來像這樣:

您需要發送的cookie與捲曲的要求,從而使會話數據可用於處理,你可以添加額外的頭捲曲的請求與-H,或明確指定該cookie:

curl --cookie "session=<encoded session>" http://localhost:5000/address/ 

瀏覽器將幫助您處理該課程的,但捲曲完全是無狀態的,不會解析和存儲Set-Cookie頭爲你默認,但如果你正在使用curl進行登錄,就可以告訴它該cookie存儲在cookie罐與-c <file>,然後你可以從它在你的下一個請求以-b file

閱讀HTTP Cookie wiki page

Curl cookie docs

Curl man page

+0

真棒!謝謝@DazWorrall – ChiliConSql

相關問題