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 中保存这样的安全令牌
  • 如何确保进一步的请求从客户端会话向我发送该令牌。

我不知道它是如何工作的,请帮助

4

2 回答 2

0

There is no way for a server to make REST clients accept and return cookies. Web browsers will do it under certain conditions when the user logs in manually, but unless your service is accessed only by interactive web applications hosted in the same domain and every user has an account on your service, you might as well forget this approach. (Even CORS won't help for browsers/users that refuse cross-domain cookies.)

The most common solution is requiring the REST client to send its credentials in every request, often using standard http auth headers, and securing the transmission with https.

OAuth/OAuth2 can be useful here if you want to separate authentication from authorization, at the expense of simplicity.

于 2013-04-13T22:36:40.710 回答
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
于 2013-04-13T22:17:44.320 回答