【问题标题】:Additional logging for django.contrib.authdjango.contrib.auth 的附加日志记录
【发布时间】:2015-09-09 04:09:12
【问题描述】:

我想在会话哈希验证失败时记录。日志代码应该插入到这个https://github.com/django/django/blob/master/django/contrib/auth/init.py#L183 if 块中。

我正在尝试找出实现这一点的最佳方法。目前看来我需要覆盖整个django.contrib.auth.middleware.AuthenticationMiddleware

你有什么建议给我吗?

【问题讨论】:

    标签: python django session authentication


    【解决方案1】:

    你为什么不复制get_user函数并将记录器放在你想要的位置:

    from django.contrib.auth import *    
    
    def your_get_user(request):
        """
        Returns the user model instance associated with the given request session.
        If no user is retrieved an instance of `AnonymousUser` is returned.
        """
        from django.contrib.auth.models import User, AnonymousUser
        user = None
        try:
            user_id = _get_user_session_key(request)
            backend_path = request.session[BACKEND_SESSION_KEY]
        except KeyError:
            pass
        else:
            if backend_path in settings.AUTHENTICATION_BACKENDS:
                backend = load_backend(backend_path)
                user = backend.get_user(user_id)
                # Verify the session
                if ('django.contrib.auth.middleware.SessionAuthenticationMiddleware'
                        in settings.MIDDLEWARE_CLASSES and hasattr(user, 'get_session_auth_hash')):
                    session_hash = request.session.get(HASH_SESSION_KEY)
                    session_hash_verified = session_hash and constant_time_compare(
                        session_hash,
                        user.get_session_auth_hash()
                    )
                    if not session_hash_verified:
                        log = logging.getLogger("YourLog")
                        log.debug(session_hash)
                        request.session.flush()
                        user = None
    
        return user or AnonymousUser()
    

    并像你想在你的代码中那样使用它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 2019-12-17
      • 2020-10-28
      • 2022-06-11
      相关资源
      最近更新 更多