2013-04-13 46 views
2

我正在開發一個項目,其中我的每個REST端點都需要進行身份驗證。一個例子是燒瓶:如何在會話中存儲憑證並檢索它們?

@login_required 
def get_transactions(self): 
    pass 

我有一個User模型,它看起來像

class User(UserMixin, db.Model): 
    __tablename__ = 'users' 
    # noinspection PyShadowingBuiltins 
    uuid = Column('uuid', GUID(), default=uuid.uuid4, primary_key=True, 
        unique=True) 
    email = Column('email', String, nullable=False, unique=True) 
    _password = Column('password', String, nullable=False) 
    created_on = Column('created_on', sa.types.DateTime(timezone=True), 
         default=datetime.utcnow(), nullable=False) 
    last_login = Column('last_login', sa.types.DateTime(timezone=True), 
         onupdate=datetime.utcnow()) 

    def __init__(self, email, password): 
     self.email = email 
     self._password = hash_password(password) # hash_password does md5 of password 
  • 一旦用戶登錄我想要存儲在客戶端會話的安全令牌,並希望每個進一步要求有該令牌
  • 我查找的例子,但不明白如何我可以在客戶端會話PLUS保存這樣的安全令牌
  • 我怎樣才能確保進一步的請求從客戶端會話向我發送該令牌。

我不知道如何工作的,請大家幫忙

回答

0

你見過這個例子嗎? http://flask.pocoo.org/docs/patterns/viewdecorators/?highlight=login_required

模塊也喜歡這些,如果你不喜歡自己改寫的事情:

無論如何,存儲在會話中的數據,即應該相當容易。簡單地把它放在flask.session:

import flask 
# You want to automatically generate the token and store it somewhere on the server (database for example) 
flask.session['some_token'] = some_token 

你的令牌可能是這樣的:

class Session(db.Model): 
    token = Column('token') # auto generated thingy 
    # foreign key to user for example 
    # expiration time/date 
0

沒有辦法對服務器進行REST客戶接受並返回餅乾。當用戶手動登錄時,Web瀏覽器會在特定條件下執行此操作,但除非您的服務僅由託管在同一個域中的交互式Web應用程序訪問,並且每個用戶都有一個服務帳戶,否則您可能會忘記此方法。 (即使CORS對於拒絕跨域cookie的瀏覽器/用戶也沒有幫助。)

最常見的解決方案是要求REST客戶端在每個請求中發送其憑據(通常使用標準http auth頭文件),並保護使用https傳輸。

如果您想要將驗證與授權分開,OAuth/OAuth2可能會很有用,但這是以簡單爲代價的。

相關問題