简体   繁体   English

Flask:如何在会话中存储凭据并检索它们?

[英]Flask: How to store credentials in session and retrieve them?

I am working on a project where each of my REST endpoints needs to be authenticated. 我正在一个项目中,我的每个REST端点都需要进行身份验证。 An example is 一个例子是

@login_required
def get_transactions(self):
  pass

I have a User model which looks like 我有一个看起来像的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
  • Once the user is logged in I want to store a security token on client session and would like each further request to have that token 用户登录后,我想在客户端会话中存储安全令牌,并希望每个其他请求都拥有该令牌
  • I looked for examples, but did not understand how I can save such a security token in client session PLUS 我查找了示例,但不了解如何在客户端会话PLUS中保存这样的安全令牌。
  • How can I make sure that further requests send me that token from client session. 我如何确保其他请求从客户端会话向我发送该令牌。

I do not know how that works, please help 我不知道它是如何工作的,请帮忙

Have you seen this example? 你看过这个例子吗? http://flask.pocoo.org/docs/patterns/viewdecorators/?highlight=login_required http://flask.pocoo.org/docs/patterns/viewdecorators/?highlight=login_required

Also modules like these if you don't feel like rewriting the thing yourself: 如果您不想自己重写内容,还可以使用以下类似模块:

Anyway, as for storing the data in the session, that should be fairly easy. 无论如何,对于在会话中存储数据,这应该相当容易。 Simply put it in flask.session: 只需将其放在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

Your token could be something like this: 您的令牌可能是这样的:

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

There is no way for a server to make REST clients accept and return cookies. 服务器无法使REST客户端接受并返回cookie。 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. 当用户手动登录时,Web浏览器会在某些条件下执行此操作,但是除非仅通过位于同一域中的交互式Web应用程序访问您的服务,并且每个用户都在您的服务上拥有一个帐户,否则您最好也不要使用此方法。 (Even CORS won't help for browsers/users that refuse cross-domain cookies.) (即使CORS对于拒绝跨域Cookie的浏览器/用户也无济于事。)

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. 最常见的解决方案是要求REST客户端在每个请求中(通常使用标准的http auth标头)发送其凭据,并使用https保护传输。

OAuth/OAuth2 can be useful here if you want to separate authentication from authorization, at the expense of simplicity. 如果您想将身份验证与授权分开(以简单性为代价),则OAuth / OAuth2在这里很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM