将应用程序级别的用户名/用户 ID 注入 nginx/Apache 日志

Posted

技术标签:

【中文标题】将应用程序级别的用户名/用户 ID 注入 nginx/Apache 日志【英文标题】:Injecting app level username/userid into nginx/Apache log 【发布时间】:2011-10-12 20:34:16 【问题描述】:

有没有办法将应用程序级别的用户名或 ID(在本例中为 django 用户名或 ID)注入 Apache 或 ngnix 日志?请注意,我不是在询问 HTTP auth 用户名。

【问题讨论】:

【参考方案1】:

我目前正在使用一个简短的自定义中间件将此数据添加到响应标头中,如下所示:

from django.utils.deprecation import MiddlewareMixin
class RemoteUserMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        if request.user.is_authenticated:
            response['X-Remote-User-Name'] = request.user.username
            response['X-Remote-User-Id'] = request.user.id
        return response

有了这个,您可以在您的 Apache 配置中使用 %X-Remote-User-Nameo and %X-Remote-User-Ido(或类似的 nginx 配置)并将信息直接放入您的日志中。

【讨论】:

【参考方案2】:

我们这样做,只是我们告诉 Apache 存储 Django sessionid cookie。

LogFormat "%h %l %u %t \"%r\" %>s %b \"%Refereri\" \"%User-agenti\" %sessionidC" withsession
CustomLog logs/example.com-access_log withsession

将 sessionid 映射到用户是一个两步过程,但它很容易实现。您可以通过设置一个带有显式 ID 的 cookie,然后使用自定义日志来捕获它来执行类似的操作。

【讨论】:

太好了,我不知道日志记录中的“C”选项,这可能会起作用。【参考方案3】:

如果您有用户名的 cookie,例如“uname”,您可以添加 %unameC,如下所示:

LogFormat "%X-Forwarded-Fori %unameC %l %u %t \"%r\" %>s %b \"%Refereri\" \"%User-Agenti\"" combined

这里的 X-Forwarded-For 是用户 ip 地址。我的应用服务器是带有 Spring 安全性的 tomcat8。输出是这样的:

24.xx.xx.xxx user.name - - [09/Sep/2016:19:33:21 -0400] "GET /xxxx HTTP/1.1" 304 - "https://xxx/xxx" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/52.0.2743.116 Safari/537.36"

【讨论】:

以上是关于将应用程序级别的用户名/用户 ID 注入 nginx/Apache 日志的主要内容,如果未能解决你的问题,请参考以下文章

第四章SQL注入----

IdentityServer:客户端级别的模拟

MQ消息头中用户id的默认值

sql注入显错注入-GET

将用户 ID 作为 url 参数是不是安全?

SQL注入详解