在与flask-restful一起使用时访问flask-socket中的JWT令牌

问题描述 投票:0回答:2

我可以使用 **get_jwt_identity()* 获取用于 get、post、put 请求的 jwt 令牌

但是我怎样才能获得它用于烧瓶插座。

def handle_message():
    emit('message_activated', {'data': 'my data', 'count': 0})

socketio.on_event('message', handle_message)
flask flask-restful flask-socketio
2个回答
0
投票

假设您使用的是 JavaScript Socket.IO 客户端,则可以使用

extraHeaders
选项来传递自定义标头。示例:

var socket = io("http://localhost:5000", {
  extraHeaders: {
    "X-My-Auth": "your-token-here"
  }
});

当然,您可以将

X-My-Auth
标头名称替换为您正在使用的标头。

在服务器中,仅当客户端连接时才会执行 Flask-SocketIO 事件的身份验证。无需验证每个事件,因为客户端和服务器之间存在永久连接。这是一个连接处理程序示例:

@socketio.event
def connect():
    token = request.headers['X-My-Auth']
    if not verify_token(token):
        return False
    # user is authenticated, proceed normally from here on

0
投票

假设您正在为套接字使用基于类的命名空间。 创建一个装饰器来验证客户端共享的令牌。我正在使用

permission.py
文件来定义装饰器。

权限.py

from flask_socketio import Namespace, emit


    def requires_authentication(f):
        def wrapper(*args, **kwargs):
            token = request.headers.get("Authorization")
            if not token:
                emit(
                    "data_fetched",
                    "token is missing",
                    namespace="/ws/active-alarms",
                    # broadcast=True,
                )
            is_valid = validate_token(token)
            if not is_valid:
                emit(
                    "data_fetched",
                    "token is expired",
                    namespace="/ws/active-alarms",
                    # broadcast=True,
                )
    
        return wrapper

套接字.py

class DummyData(Namespace):

    @requires_authentication
    def on_connect(self):
        print("********connection establised*************")

    def on_disconnect(self):
        print("********closing the connections*************")

    @requires_authentication
    def on_fetch_data(self, pagination_data):
        error = {"code": 500, "message": ""}
        try:
            # your logic
        except Exception as e:
            message = str(e)
            error["message"] = message
            emit(
                "data_fetched",
                error,
                namespace="/ws/active-alarms",
                # broadcast=True,
            )
© www.soinside.com 2019 - 2024. All rights reserved.