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

。_饼干妹妹 提交于 2020-01-25 04:12:41

问题


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..


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3379353/django-auth-how-to-disallow-user-session-if-his-ip-doesnt-match-the-original-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!