开发者

Django auth: How to disallow user session if his IP doesn't match the original one(the one he logged in with)

How can auth can be configured or modified to disallow user sessions if the user's IP is not the same IP that he logged in with ? I really try to protect my Django site from XSS as much as I can. But I never can be sure that I covered all the bases. If worst comes to worst and someone is able to put some XSS in my site, at least this could 开发者_如何学运维prevent him from hijacking existing user sessions..


Use the following just to be sure you are getting the real IP address of the visitor and not that of the proxy or the load balancer. (just in case your server is behind one)

# on login:
request.session['logged_ip'] = request.META.get('HTTP_X_FORWARDED_FOR',
                                request.META.get('HTTP_X_REAL_IP',
                                 request.META.get('REMOTE_ADDR', '1.2.3.4')))

# on each request
if (request.META.get('HTTP_X_FORWARDED_FOR',
    request.META.get('HTTP_X_REAL_IP',
    request.META.get('REMOTE_ADDR', '1.2.3.4'))) != request.session['logged_ip'])
    # don't allow


In your User model class create an IP field that stores the IP address of the request.

original_ip_address = request.META['REMOTE_ADDR']

then before serving a view simply check the current request with the stored ip:

if request.META['REMOTE_ADDR'] == ip_from_database: `
# Do something
else:
 #redirect to login

you can make the above a function that is always called before anything else in a view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜