flask_jwt 机制

在前后端分离的趋势下,csrf防护变得越来越困难, 而jwt认证机制正好能避开这个问题。

1,实例化

from flask_jwt import JWT
jwt = JWT()

2,设置必要参数

JWT_SECRET_KEY=xxx

3,实现jwt最基本功能,authenticate 、identity,通过钩子实现

def configure_jwt(jwt):
    """
    configure handlers to flask_jwt
    """

    @jwt.authentication_handler
    def authenticate(account, password):
        """ 
        实现账号的验证逻辑,并返回自定义数据,该数据会在下面identity函数中通过payload['identity']
        取到
        """
        pass
        

    @jwt.identity_handler
    def identity(payload):
        """ 
        接受一个 payload 对象作为参数,并返回根据payload['identity']的值查找对应的信息。返回 
        的数据, current_identity(from jwt import current_identiy)会用到
        """
        pass

4,初始化

from flask import Flask

app = Flask(__name__)
config_jwt(jwt)
jwt.init_app(app)

5,使用

from flask_jwt import jwt_required, current_identity

api.route('api/v1/test', methods=['POST'])
@jwt_required
def api():
    role = current_identity.role
    pass

6, 其他可自定义功能

    def _jwt_error_callback(self, error):
        return self.jwt_error_callback(error)

    def authentication_handler(self, callback):
        """Specifies the identity handler function. This function receives two positional
        arguments. The first being the username the second being the password. It should return an
        object representing an authenticated identity. Example::

            @jwt.authentication_handler
            def authenticate(username, password):
                user = User.query.filter(User.username == username).scalar()
                if bcrypt.check_password_hash(user.password, password):
                    return user

        :param callback: the identity handler function
        """
        self.authentication_callback = callback
        return callback

    def identity_handler(self, callback):
        """Specifies the identity handler function. This function receives one positional argument
        being the JWT payload. For example::

            @jwt.identity_handler
            def identify(payload):
                return User.query.filter(User.id == payload['identity']).scalar()

        :param callback: the identity handler function
        """
        self.identity_callback = callback
        return callback

    def jwt_error_handler(self, callback):
        """Specifies the error handler function. Example::

            @jwt.error_handler
            def error_handler(e):
                return "Something bad happened", 400

        :param callback: the error handler function
        """
        self.jwt_error_callback = callback
        return callback

    def auth_response_handler(self, callback):
        """Specifies the authentication response handler function.

        :param callable callback: the auth response handler function
        """
        self.auth_response_callback = callback
        return callback

    def auth_request_handler(self, callback):
        """Specifies the authentication response handler function.

        :param callable callback: the auth request handler function

        .. deprecated
        """
        warnings.warn("This handler is deprecated. The recommended approach to have control over "
                      "the authentication resource is to disable the built-in  resource by "
                      "setting JWT_AUTH_URL_RULE=None and registering your own authentication "
                      "resource directly on your application.", DeprecationWarning, stacklevel=2)
        self.auth_request_callback = callback
        return callback

    def request_handler(self, callback):
        """Specifieds the request handler function. This function returns a JWT from the current
        request.

        :param callable callback: the request handler function
        """
        self.request_callback = callback
        return callback

    def jwt_encode_handler(self, callback):
        """Specifies the encoding handler function. This function receives a payload and signs it.

        :param callable callback: the encoding handler function
        """
        self.jwt_encode_callback = callback
        return callback

    def jwt_decode_handler(self, callback):
        """Specifies the decoding handler function. This function receives a
        signed payload and decodes it.

        :param callable callback: the decoding handler function
        """
        self.jwt_decode_callback = callback
        return callback

    def jwt_payload_handler(self, callback):
        """Specifies the JWT payload handler function. This function receives the return value from
        the ``identity_handler`` function

        Example::

            @jwt.payload_handler
            def make_payload(identity):
                return {'user_id': identity.id}

        :param callable callback: the payload handler function
        """
        self.jwt_payload_callback = callback
        return callback

    def jwt_headers_handler(self, callback):
        """Specifies the JWT header handler function. This function receives the return value from
        the ``identity_handler`` function.

        Example::

            @jwt.payload_handler
            def make_payload(identity):
                return {'user_id': identity.id}

        :param callable callback: the payload handler function
        """
        self.jwt_headers_callback = callback
        return callback

注: 该package 2015年最后更新,作者建议如果要用新的package 可以用flask-jwt-simple 和flask-jwt-extend

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Flask 中实现 Token 机制,可以使用 JWT(JSON Web Tokens)库。下面是一个简单的示例代码: ```python from flask import Flask, request from flask_jwt import JWT, jwt_required, current_identity from werkzeug.security import safe_str_cmp app = Flask(__name__) app.config['SECRET_KEY'] = 'super-secret' app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=1) class User: def __init__(self, id, username, password): self.id = id self.username = username self.password = password def __str__(self): return f"User(id='{self.id}')" users = [ User(1, 'user1', 'password1'), User(2, 'user2', 'password2'), ] def authenticate(username, password): user = next((user for user in users if user.username == username), None) if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')): return user def identity(payload): user_id = payload['identity'] return next((user for user in users if user.id == user_id), None) jwt = JWT(app, authenticate, identity) @app.route('/protected') @jwt_required() def protected(): return f'Hello, {current_identity}!' if __name__ == '__main__': app.run() ``` 在上面的代码中,我们首先定义了一个 `User` 类来存储用户信息。然后定义了一个 `authenticate` 函数来用于用户认证,它会查找用户列表中是否存在指定的用户名和密码。如果存在,则返回该用户对象。 接下来,我们定义了一个 `identity` 函数,它会根据 JWT 中存储的用户 ID 来查找用户对象。最后,我们创建了一个 `jwt` 对象,并将其绑定到 Flask 中。 最后,我们定义了一个受保护的路由 `/protected`,并使用 `@jwt_required()` 装饰器来保护它。这意味着在访问该路由时,用户必须先提供有效的 JWT 才能继续访问。 当用户成功提供有效的 JWT 且通过身份验证时,`current_identity` 会返回该用户对象,我们可以在响应中使用它。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值