cookie、session、csrf
cookie的设置和获取
import time
from tornado.web import RequestHandler class IndexHandle(RequestHandler):
def get(self):
# 设置cookie
self.set_cookie('username', 'ivy')
# 设置过期时间为60s
self.set_cookie('username', 'ivy', expires=time.time() + 60)
# 设置过期时间为2天
self.set_cookie('username', 'ivy', expires_days=2)
# 当httponly为True时,网页的js代码无法获取该cookie
self.set_cookie('username', 'ivy', httponly=True)
# 设置cookie的过期时间为2分钟,max_age的优先级大于expires
self.set_cookie('username', 'ivy', max_age=120, expires=time.time() + 60)
# 设置加密的cookie,设置加密必须到app的里面去新增一个cookie_secret的参数,让这个参数等于一个字符串(盐)
self.set_secure_cookie('username', 'ivy') # 获取cookie
self.get_cookie('ivy')
# 获取加密的cookie, 返回字节数据
self.get_secure_cookie('username')
登录验证
from tornado.web import RequestHandler, Application, authenticated
from tornado.httpserver import HTTPServer
from tornado.options import options, define
from tornado.ioloop import IOLoop
from util import uimethods, uimodules define('port', default=7981, type=int) class BaseHandle(RequestHandler):
def get_current_user(self):
current_user = self.get_secure_cookie('username')
if current_user:
return current_user
return None class IndexHandle(BaseHandle):
@authenticated
def get(self):
self.render('index.html') class LoginHandle(RequestHandler):
def get(self):
self.render('login.html') def post(self):
username = self.get_argument('username')
password = self.get_argument('password')
if username == password:
self.set_cookie(username, password)
self.write('登录成功!') application = Application(
handlers=[
(r'/index', IndexHandle),
(r'/login', LoginHandle),
],
template_path='templates',
ui_methods=uimethods,
ui_modules=uimodules,
login_url='/login',
) if __name__ == '__main__':
options.parse_command_line()
app = HTTPServer(application)
app.listen(options.port)
IOLoop.current().start()
- 在登录成功之后设置cookie
- 新建base类,重写get_current_user方法
- get_current_user:当当前的cookie中有特定的值的时候,返回该值
- 导入authenticated方法
- 在需要检测时候登录的方法页面调用该函数(装饰器的方法)
- 在app里面配置一条login_url的参数,当检测到未登录的时候(get_current_user返回None)就让页面跳转到该路由下
验证登录后跳转回原页面
from tornado.web import RequestHandler, authenticated class BaseHandle(RequestHandler):
def get_current_user(self):
current_user = self.get_cookie('login')
if current_user:
return current_user class IndexHandle(BaseHandle):
@authenticated
def get(self):
self.write('index 页面') class LoginHandle(BaseHandle):
def get(self):
next_url = self.get_argument('next', '')
self.render('login.html', next_url=next_url) def post(self):
username = self.get_argument('username', '')
password = self.get_argument('password', '')
next_url = self.get_argument('next', '')
if username == password and next_url:
self.set_secure_cookie('login', 'true')
self.redirect(next_url)
elif username == password:
self.set_secure_cookie('login', 'true')
self.write('登录成功!')
from tornado.web import Application
from tornado.options import options
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import handles settings = {
'template_path': 'templates',
'static_path': 'static',
'cookie_secret': 'summer',
'login_url': '/login' } urlpatterns = [
(r'/login', handles.LoginHandle),
(r'/index', handles.IndexHandle),
] app = Application(handlers=urlpatterns, **settings) if __name__ == '__main__':
options.parse_command_line()
http = HTTPServer(app)
http.listen(80)
IOLoop.current().start()
- 当用户未登录直接访问index页面的时候,因为配置了验证登录(authenticated),所以他会直接跳转到login_url,并且url附带next参数
- 在登录页面获取这个next参数,如果没有默认为空,将这个参数传到页面的action中
- 在form表单提交后,在post方法里获取这个next参数,如果用户名和密码正确,并且存在这个next参数,就直接跳转到next参数所指向的url
- 若没有,就跳到正常登陆页面。
Session
- 使用前的配置:
- pip install redis
- pip install pycket
- settings配置:
from tornado.web import Application
from tornado.options import options
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import handles settings = {
'template_path': 'templates',
'static_path': 'static',
'cookie_secret': 'summer',
'login_url': '/login',
'pycket': {
'engine': 'redis',
'storage': {
'host': 'localhost',
'port': 6379,
'db_sessions': 6,
'db_notifications': 11,
'max_connections': 3 * 10,
},
'cookies': {
'expires_days': 7,
'max_age': 100
},
},
} urlpatterns = [
(r'/login', handles.LoginHandle),
(r'/index', handles.IndexHandle),
] app = Application(handlers=urlpatterns, **settings) if __name__ == '__main__':
options.parse_command_line()
http = HTTPServer(app)
http.listen(1996)
IOLoop.current().start()如果redis有密码,在配置项里加一个password就可以了
- 使用:
from tornado.web import RequestHandler, authenticated
from pycket.session import SessionMixin class BaseHandle(RequestHandler, SessionMixin):
def get_current_user(self):
current_user = self.session.get('login')
if current_user:
return current_user class IndexHandle(BaseHandle):
@authenticated
def get(self):
self.write('index 页面') class LoginHandle(BaseHandle):
def get(self):
next_url = self.get_argument('next', '')
self.render('login.html', next_url=next_url) def post(self):
username = self.get_argument('username', '')
password = self.get_argument('password', '')
next_url = self.get_argument('next', '')
if username == password and next_url:
self.session.set('login', 'true')
self.redirect(next_url)
elif username == password:
self.set_secure_cookie('login', 'true')
self.write('登录成功!') - 导入SessionMinxin
- 让BaseHandle继承自SessionMinxin
- 设置session
- self.session.set(key, value)
- 获取session
- self.session.get(key)
xsrf:
在form表单的html里面加入{% module xsrf_form_html() %}即可
cookie、session、csrf的更多相关文章
- Django之Cookie、Session、CSRF、Admin
Django之Cookie.Session.CSRF.Admin Cookie 1.获取Cookie: 1 2 3 4 5 6 request.COOKIES['key'] request.get ...
- 【python】-- Django 分页 、cookie、Session、CSRF
Django 分页 .cookie.Session.CSRF 一.分页 分页功能在每个网站都是必要的,下面主要介绍两种分页方式: 1.Django内置分页 from django.shortcuts ...
- 傻傻分不清之 Cookie、Session、Token、JWT
傻傻分不清之 Cookie.Session.Token.JWT 什么是认证(Authentication) 通俗地讲就是验证当前用户的身份,证明“你是你自己”(比如:你每天上下班打卡,都需要通过指纹打 ...
- 还分不清 Cookie、Session、Token、JWT?一篇文章讲清楚
还分不清 Cookie.Session.Token.JWT?一篇文章讲清楚 转载来源 公众号:前端加加 作者:秋天不落叶 什么是认证(Authentication) 通俗地讲就是验证当前用户的身份,证 ...
- Cookie、Session、Token与JWT(跨域认证)
之前看到群里有人问JWT相关的内容,只记得是token的一种,去补习了一下,和很久之前发的认证方式总结的笔记放在一起发出来吧. Cookie.Session.Token与JWT(跨域认证) 什么是Co ...
- [转]cookie、session、sessionid 与jsessionid
cookie.session.sessionid 与jsessionid,要想明白他们之间的关系,下面来看个有趣的场景来帮你理解. 我们都知道银行,银行的收柜台每天要接待客户存款/取款业务,可以有几种 ...
- cookie、session、sessionid ,jsessionid 的区别
本文是转载虫师博客的文章http://www.cnblogs.com/fnng/archive/2012/08/14/2637279.html cookie.session.sessionid 与js ...
- application、session、request、page的作用范围、Application,Session和Cookie的区别
Web应用中的JSP和servlet都是由web服务器来调用,Jsp和Servlet之间通常不会相互调用,那么Jsp和Servlet之间交换数据就要用到application.session.requ ...
- cookie、session、token的区别与联系
https://www.cnblogs.com/moyand/p/9047978.html cookie.session.token存在意义 http协议是无状态协议,请求之间是没有联系的,cooki ...
- 3 分钟带你深入了解 Cookie、Session、Token
经常会有用户咨询,CDN 是否会传递 Cookie 信息,是否会对源站 Session 有影响,Token 的防盗链配置为什么总是配置失败?为此,我们就针对 Cookie.Session 和 Toke ...
随机推荐
- Vue2.0 【第一季】第7节 v-bind指令
目录 Vue2.0 [第一季] 第7节 v-bind指令 第7节 v-bind指令 v-bind缩写 绑定CSS样式 Vue2.0 [第一季] 第7节 v-bind指令 第7节 v-bind指令 v- ...
- Windows下EDK2环境的搭建以及经典的程序设计Print Hello World !-----(Linux下的待后续熟练了再更新)
很久没有更新博客了,之前的博客末尾有提到过要写有关EDK2环境搭建的博客,现在就是完成的时候了,后续博客更新会比较规律(大概每周一篇?) 本人博客仅仅发表于博客园,本人主页为 http ...
- 微信公众号 H5页面 支付注意细节
1. 当秘钥(AppSecretApplets) 有问题时注意是不是已经被重置过了,此时要注意获取最新的秘钥: 2. 调试时后端的东西要放在线上https 请求 不然在手机上测试时 会被拦截: ...
- Python文本文件读写操作时的字符编码问题
说明:文本文件的字符编码问题只存在t模式中,如:open('a.txt', mode='rt') 编码(encode): 我们输入的任何字符想要以文件(如.txt)的形式保存在计算机的硬盘上, 必须先 ...
- ElegantSnap 一个优雅的,易用的iOS/tvOS/macOS自动布局框架, 超级详细的使用教程,多视图水平等宽/垂直等高排列
ElegantSnap ElegantSnap(Base on SnapKit) to make Auto Layout easy and elegant on both iOS and OS X. ...
- 【面试必备】用了那么多次 ping,是时候知道 ping 是如何工作的了!
每日一句英语学习,每天进步一点点: 前言 在日常生活或工作中,我们在判断与对方网络是否畅通,使用的最多的莫过于 ping 命令了. “那你知道 ping 是如何工作的吗?” —— 来自小林的灵魂拷问 ...
- CSS劫持攻击
CSS劫持攻击 CSS劫持是一种并不很受重视的劫持方式,但是其也有一定的危害,且由于其并不一定需要依赖JavaScript,这使得此种攻击方式更容易实现. ClickJacking点击劫持 当访问某网 ...
- [Docker7]Harbor
harbor download harbor offline tar package wget https://github.com/vmware/harbor/releases/download/v ...
- JDBC开源框架:DBUtils自定义业务类型相关转换器
dbutils提供的handler转换不能满足实际业务开发的需求.比如枚举转int,时间类型LocalDateTime,实体对象的属性名与字段未能相对应. mysql表member结构字段: id.m ...
- 基本的访问控制列表ACL配置
摘要: 访问控制列表ACL (Access Control L ist)是由permit或 deny语句组成的一系列有顺序的规则集合,这些规则根据数据包的源地址.目的地址.源端口.目的端口等信息 来 ...